Lesson · Python for Beginners
Lists and indexing
A list groups values so a program can process related items together.
What you will learn
- Create and index a list
- Append an item
- Iterate over list values
An ordered collection
A list is written with square brackets and can hold values in a defined order. The first item is at index zero, not one. Negative indices count backward from the end. An index that does not exist raises IndexError, so check the list length or use a loop when the position is uncertain.
Change a list deliberately
Lists are mutable: methods such as append add an item to the same list. The list's length changes, but existing items keep their relative order. Use remove when you know the value to delete, and pop when you need to remove an item at a position and keep that item as a result.
Visit every item
A for loop can visit each list value without manually calculating its index. This is usually clearer when the task only needs each value. If both an index and a value are needed, enumerate returns them together. Avoid changing the list's length while iterating over that same list.
Keep related values together
Use a list when order matters and values play a similar role, such as a set of tasks or scores. A list can hold different types, but mixing unrelated types can make later code harder to reason about. Start with a consistent collection and choose a more descriptive data structure when the problem calls for one.
Know when two names share a list
Assigning one list variable to another does not copy the list; both names refer to the same mutable object. Changing an item through either name is visible through the other. If an independent shallow copy is needed, use a copying operation and remember that nested objects inside it may still be shared.
topics = ['HTML', 'CSS']
topics.append('Python')
for topic in topics:
print(topic)
Expected output
HTML
CSS
Python
Practice exercise
Create a list of three study topics and print each topic on its own line.
Show a hint
Use a for loop instead of printing each item separately.
Show one possible solution
topics = ['loops', 'functions', 'lists']; for topic in topics: print(topic) prints each value once.
Quick check
Python sequences use zero-based indexing.