Python Lists
In this page:
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])
print(items[-1])
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
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:
print(item)
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: