Python Lists
A list is an ordered, changeable collection of items. It is Python's most-used data structure: a shopping list, the rows of a spreadsheet, the scores in a game. Lists are written with square brackets and commas.
fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, True, None]
empty = []
print(fruits)
print(mixed)
print(len(fruits), len(empty))['apple', 'banana', 'cherry']
[1, 'two', 3.0, True, None]
3 0
Key properties
| Property | Meaning |
|---|---|
| Ordered | Items keep the position you put them in |
| Indexed | Access items by position, starting at 0 |
| Mutable | You can add, remove and change items |
| Allows duplicates | [1, 1, 1] is perfectly fine |
| Any types | Items can be of different types, even other lists |
Accessing items
Indexing and slicing work exactly like they do for strings:
colors = ["red", "orange", "yellow", "green", "blue"]
print(colors[0])
print(colors[-1])
print(colors[1:3])
print(colors[::-1])
print("green" in colors)
print(colors.index("yellow"))red
blue
['orange', 'yellow']
['blue', 'green', 'yellow', 'orange', 'red']
True
2
Asking for an index that doesn't exist raises an IndexError.
Changing items
Unlike strings, lists can be modified in place — one item, or a whole slice at once:
nums = [10, 20, 30, 40, 50]
nums[0] = 11
print(nums)
nums[1:3] = [21, 22, 23] # replace two items with three
print(nums)
nums[-2:] = [] # delete the last two
print(nums)[11, 20, 30, 40, 50]
[11, 21, 22, 23, 40, 50]
[11, 21, 22, 23]
Looping through a list
A for loop visits each item in order. Use enumerate() when you also need the position:
tasks = ["write code", "test it", "ship it"]
for task in tasks:
print("-", task)
for i, task in enumerate(tasks, start=1):
print(f"{i}. {task}")- write code
- test it
- ship it
1. write code
2. test it
3. ship it
Combining lists
a = [1, 2]
b = [3, 4]
print(a + b) # concatenation creates a new list
print(a * 3) # repetition
print(sum(a + b), max(b), min(a))
print(sorted([3, 1, 2]))[1, 2, 3, 4]
[1, 2, 1, 2, 1, 2]
10 4 1
[1, 2, 3]
Nested lists
A list can contain other lists, which is a simple way to represent a grid or table:
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print(grid[1]) # the middle row
print(grid[1][2]) # row 1, column 2
for row in grid:
print(" ".join(str(n) for n in row))[4, 5, 6]
6
1 2 3
4 5 6
7 8 9
Copying a list
Remember that b = a does not copy — it creates a second name for the same list. To get an independent copy use a.copy(), list(a) or a[:]:
original = ["x", "y"]
same = original
copy = original.copy()
original.append("z")
print(same)
print(copy)['x', 'y', 'z']
['x', 'y']
Note: These are shallow copies: nested lists inside are still shared. Use
copy.deepcopy()from thecopymodule when you need to copy nested structures too.
Test yourself
What is ["a", "b", "c", "d"][1:3]?
- ["a", "b"]
- ["b", "c"]
- ["b", "c", "d"]
- ["c", "d"]
After a = [1]; b = a; b.append(2), what is a?
- [1]
- [1, 2]
- [2]
- An error
Which of these makes an independent (shallow) copy of list a?
- b = a
- b = a.copy()
- b is a
- b = &a