← Python lessons

Lists

A list holds several values in order, inside square brackets. It is Python's everyday container for "a bunch of things".

Making a list

rolls = [3, 5, 2]
names = ["Alice", "Bob", "Cara"]
empty = []

Reading by position (index)

Lists use the same zero-based and negative indexing rules you used with strings.

Positions are counted from 0, not 1:

rolls = [3, 5, 2]
print(rolls[0])
print(rolls[2])
print(rolls[-1])

rolls[0] is the first item, rolls[2] the third. rolls[-1] counts from the end, so it is the last item whatever the length of the list.

How many items?

len() counts the items in a list:

rolls = [3, 5, 2]
print(len(rolls))

Is a value in the list?

The in operator also works on lists: it checks whether an item is present.

in gives back True or False:

rolls = [3, 5, 2]
print(5 in rolls)
print(1 in rolls)

Adding items

Use .append() to add one value to the end of a list:

scores = []
scores.append(3)
scores.append(5)
print(scores)

.append(value) changes the existing list and returns None. Call it on its own line: scores.append(3). Do not write scores = scores.append(3), because that would replace scores with None.

Taking part of a list

A slice includes the start position and excludes the stop position:

scores = [9, 7, 5, 3]
print(scores[0:2])
print(scores[0:10])

A stop beyond the list's length includes all remaining items.

Leaving out a slice's start means start at zero: scores[:2] is the same as scores[0:2]. A stop of zero gives an empty list. Slicing creates a new list and leaves the original list unchanged.

Visiting every item

To do something with each item in turn, loop over the list — see For loops.

See also: Unpacking, For loops.

Your turn

The list already contains two scores. Append 8, then print the whole list. Keep the existing scores.

scores = [2, 6]
# Append the new score, then print scores.

Expected output

[2, 6, 8]

Optional review: create [3, 5, 2, 6], then print its first item and its length on separate lines. The expected lines are 3 and 4.


Practise this in the free Python course, where every exercise checks your code instantly.