← All concepts

Lecture 2

Lists

A list holds many values in order. You can index it, slice it and change it.

Indexing and slicing

Counting starts at 0; -1 is the last item. A slice [start:stop] stops before stop, and leaving a side out runs to that end.

weights = [21, 19, 25, 23]
print(weights[0], weights[-1])
print(weights[1:3], weights[:2])

Output

21 23
[19, 25] [21, 19]

Changing a list

.append() adds to the end, .insert() at a position, and x[i] = value replaces an item. len(), sum(), min() and max() summarise a list of numbers.

weights = [21, 19, 25]
weights.append(23)
weights[0] = 22
print(weights, len(weights), sum(weights) / len(weights))

Output

[22, 19, 25, 23] 4 22.25

Going further

From the advanced notebook — this is what the advanced questions test.

Two names, one list

b = a does not copy a list: both names point to the same list, so a change through one shows up in the other. .copy() makes an independent list.

a = [3, 1, 2]
b = a
c = a.copy()
a.append(9)
print(b, c)

Output

[3, 1, 2, 9] [3, 1, 2]

sort() versus sorted()

.sort() reorders the list itself and returns None. sorted() gives back a new sorted list and leaves the original alone.

x = [5, 2, 8]
y = sorted(x)
print(x, y)
print(x.sort(), x)

Output

[5, 2, 8] [2, 5, 8]
None [2, 5, 8]

Lists inside lists

Each item can itself be a list. Index twice: first the row, then the item in it.

plate = [[1, 2, 3], [4, 5, 6]]
print(plate[1], plate[1][2])

Output

[4, 5, 6] 6