Python Lists
In this page:
list_name = [item1, item2, item3]
list_name[index]
What is a List?
A list stores an ordered sequence of items that can be changed after creation, and unlike arrays in many other languages it can freely mix types (numbers, strings, even other lists) in the same list.
It's the default general-purpose container you reach for in Python.
Example: What is a List?
mixed = [1, "two", 3.0, [4]]
print(mixed)
Accessing List Items
Square-bracket indexing starts at 0 for the first element, and negative indices count backward from the end so my_list[-1] always gives you the last item without needing to know the list's length.
Example: Accessing List Items
items = [10, 20, 30]
print(items[0]) # first item, index 0
print(items[-1]) # last item, negative index counts from the end
List Slicing
Slicing with list[start:end] pulls out a sub-list without modifying the original, and because the end index is exclusive, list[0:3] gives exactly three elements -- a detail that trips up beginners coming from languages with inclusive ranges.
Example: List Slicing
items = [10, 20, 30, 40, 50]
print(items[0:3])
Modifying List Items
Because lists are mutable, you can reassign my_list[i] = new_value to change an element in place without creating a new list object, which matters for performance and also means two variables pointing at the same list will both see the change.
Example: Modifying List Items
items = [10, 20, 30]
items[1] = 99 # reassigns the element at index 1 in place
print(items)
Iterating over Lists
A for loop over a list yields each element directly in order (not the index), which is the idiomatic way to process items -- reach for enumerate() only when you also need the position of each item.
Example: Iterating over Lists
items = [10, 20, 30]
for item in items: # yields each value directly, not the index
print(item)
- Using an index past the end, as in
items[len(items)], which raisesIndexErrorbecause the last valid index islen(items) - 1. - Copying a list with
b = a, which only creates a second name for the same list, so changingbalso changesa; usea.copy()ora[:]. - Removing or adding items while looping over the same list, which skips elements because the indexes shift during iteration.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: