Lists

A list is an ordered, changeable collection — Python's most-used data structure. Lists hold shopping items, rows from a file, results from a search: any sequence of things you want to keep in order, add to, remove from and loop over.

Creating lists

PY create.py
fruits = ["apple", "banana", "cherry"]
numbers = [3, 1, 4, 1, 5]
mixed = ["text", 42, 3.14, True, None, [1, 2]]
empty = []

print(fruits)
print(len(numbers), len(empty))
print(list("abc"), list(range(4)))
Output
['apple', 'banana', 'cherry']
5 0
['a', 'b', 'c'] [0, 1, 2, 3]

Lists use square brackets and can hold any mix of types, including other lists. list() builds a list from any iterable.

Indexing

PY index.py
colors = ["red", "green", "blue", "yellow"]

print(colors[0])
print(colors[2])
print(colors[-1])
print(colors[-2])
Output
red
blue
yellow
blue

Indexes start at 0; negative indexes count from the end, so [-1] is always the last item. Reading an index that doesn't exist raises an IndexError.

Changing items

PY change.py
scores = [70, 85, 90]
scores[0] = 75
scores[-1] += 5
print(scores)

scores[1:3] = [88, 99, 100]
print(scores)
Output
[75, 85, 95]
[75, 88, 99, 100]

Lists are mutable: you can change items in place, including replacing a whole slice with a different number of items.

Slicing

PY slice.py
letters = ["a", "b", "c", "d", "e", "f"]

print(letters[1:4])
print(letters[:3])
print(letters[3:])
print(letters[::2])
print(letters[::-1])
Output
['b', 'c', 'd']
['a', 'b', 'c']
['d', 'e', 'f']
['a', 'c', 'e']
['f', 'e', 'd', 'c', 'b', 'a']

Slices work exactly as they do for strings and always return a new list (lesson 26 covers them in depth).

Membership and length

PY membership.py
guests = ["Ana", "Ben", "Cleo"]

print("Ben" in guests)
print("Dan" not in guests)
print(len(guests))
print(guests.index("Cleo"))
print(guests.count("Ana"))
Output
True
True
3
2
1

Combining lists

PY combine.py
a = [1, 2]
b = [3, 4]

print(a + b)
print(a * 3)
print([*a, *b, 5])
Output
[1, 2, 3, 4]
[1, 2, 1, 2, 1, 2]
[1, 2, 3, 4, 5]

Nested lists

PY nested.py
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]

print(matrix[1][2])
for row in matrix:
    print(" ".join(str(n) for n in row))
Output
6
1 2 3
4 5 6
7 8 9

Lists are references

Assigning a list to another name doesn't copy it — both names refer to the same list:

PY references.py
original = [1, 2, 3]
alias = original
copy = original.copy()

alias.append(4)
print(original)
print(copy)
Output
[1, 2, 3, 4]
[1, 2, 3]

To get an independent list, copy it: lst.copy(), list(lst) or lst[:]. These are shallow copies; for lists containing other lists, use copy.deepcopy.

Trap: grid = [[0] * 3] * 3 creates three references to the same inner list — changing grid[0][0] changes every row. Use a comprehension instead: [[0] * 3 for _ in range(3)].

Useful built-in functions

PY builtins.py
nums = [4, 8, 15, 16, 23, 42]

print(len(nums), sum(nums), min(nums), max(nums))
print(sorted(nums, reverse=True))
print(list(reversed(nums)))
print(sum(nums) / len(nums))
Output
6 108 4 42
[42, 23, 16, 15, 8, 4]
[42, 23, 16, 15, 8, 4]
18.0

Try it yourself

Try it yourself
Console output