Lists
A list holds several values in order, inside square brackets. Below, you make one list of dice rolls, read it, and change it.
Making a list
Put the items between [ and ], with commas between them:
rolls = [3, 5, 2]print(rolls)It printed the whole list: [3, 5, 2]. An empty list is just [].
Reading by position (index)
Each item has a position, called its 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 the list:
rolls = [3, 5, 2]print(len(rolls))It printed 3. The last index is always one less than len().
Is a value in the list?
The in operator checks whether the list holds a value. It gives back True
or False:
rolls = [3, 5, 2]print(5 in rolls)print(1 in rolls)Adding items
.append() adds one value to the end of the list:
rolls = [3, 5, 2]rolls.append(6)print(rolls)It printed [3, 5, 2, 6]. .append() changes the list itself and returns
None. Write rolls.append(6) on its own line, never
rolls = rolls.append(6): that replaces rolls with None.
Removing items
.remove() takes the first matching value out of the list:
rolls = [3, 5, 2]rolls.remove(5)print(rolls)It printed [3, 2]. Removing a value that is not in the list raises
an error, so check with in first when you are not sure it is there.
See also: Unpacking, For loops.
Your turn
The list already holds two scores. Append 8, then print the whole list.
[2, 6, 8]
scores = [2, 6]# append 8, then print scoresAdvanced reading
- List slicing and joining — build new lists with slices,
+and*. - List methods —
insert(),pop(),sort(),index(),count()and more. - Names and references — why two names can change the same list, and how
copy()avoids it. - List comprehension — build a list from a loop in one line.