22. Lists
A list is one of Python's built-in data structures. It holds an ordered sequence of values — numbers, strings, booleans, or a mix — and lets you add, remove, and reorder items freely.
Creating a list
A list literal uses square brackets with commas between the values:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[2]) # cherryImportant: Python lists are 0-indexed. The first
item is at position 0, not 1. This is
different from how we count in everyday life, so it trips up nearly
every beginner at least once.
fruits[0]is"apple"— the first item.fruits[1]is"banana"— the second item.fruits[2]is"cherry"— the third item.
A list with three items has valid positions 0,
1, and 2. Position 3 does not
exist and raises an IndexError.
Length with len
len(t) returns the number of items in the list:
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # 3
print(fruits[len(fruits) - 1]) # cherry (the last one)Because the last valid index is always len(t) - 1,
Python offers a shortcut: negative indices count from the end.
t[-1] is always the last item:
print(fruits[-1]) # cherry
print(fruits[-2]) # bananaLooping over a list
Two natural ways to walk through a list.
for loop
The simplest loop gives you each value in order:
for item in fruits:
print(item)Output:
apple
banana
cherry
enumerate —
index and value together
When you also need the position, use enumerate. By
default it starts counting at 0:
for index, value in enumerate(fruits):
print(index, value)Output:
0 apple
1 banana
2 cherry
If you want 1-based display numbers (for user-facing output), pass a start argument:
for index, value in enumerate(fruits, 1):
print(f"{index}. {value}")Output:
1. apple
2. banana
3. cherry
Open exercises/22/01-list-loop.py. Add a fourth fruit
and re-run. Both len(fruits) and the loop should adjust
automatically.
Adding and removing items
Append to the end with .append:
fruits = ["apple", "banana"]
fruits.append("cherry") # add to the end
print(fruits[-1]) # cherry.insert(i, value) inserts at position i and
shifts later items right. Remember: positions are 0-indexed, so position
0 is the very beginning:
fruits.insert(0, "apricot") # new first item
print(fruits[0]) # apricot
print(fruits[1]) # apple (shifted from 0 to 1).pop() removes and returns the last item.
.pop(i) removes position i:
fruits.pop() # removes the last item
fruits.pop(0) # removes the first itemDo not set a slot to None
(fruits[1] = None) to "remove" an item. That replaces the
value with None but keeps the slot, leaving a hole in your
list. Use .pop(i) or del fruits[i] to remove a
slot cleanly.
Lists are passed by reference
Lists behave differently from numbers and strings in one important way: assigning a list to another variable does not make a copy.
a = [1, 2, 3]
b = a # b refers to the SAME list
b[0] = 99
print(a[0]) # 99 (the change shows through a too)Both a and b name one list. For a real
copy, use .copy() or the slice a[:]:
c = a.copy()
c[0] = 0
print(a[0]) # 99 (a is unchanged)Homework
Problem 1 — Favourite games
Open exercises/22/homework/01-favourite-games.py. Create
a list of five game names. With a
for ... in enumerate(..., 1): loop, print each as
1. Roblox, 2. Minecraft, and so on.
Problem 2 — Sum the list
Open exercises/22/homework/02-sum-list.py. A list of
numbers is declared at the top. Compute and print its sum.
Problem 3 — Insert and remove
Open exercises/22/homework/03-insert-remove.py. The
starter has a short list. Do four things, printing the full list after
each step:
- Append a new item.
- Insert another item at position 0.
- Remove the last item.
- Remove the item at position 1.
Challenge — Reverse a list
Open exercises/22/homework/04-reverse.py. Define a
function reverse(lst) that returns a new list with
the items reversed, leaving the original unchanged. Test it on a list of
strings and print both before and after.
Stuck or finished? Open the homework solutions page.