9.2. Lists are mutable¶
The syntax for accessing the elements of a list is the same as for accessing the characters of a string: the bracket operator. The expression inside the brackets specifies the index. Remember that the indices start at 0:
>>> print(cheeses[0])
Cheddar
Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list. When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned.
The one-th element of numbers
, which used to be 123, is
now 5.
You can think of a list as a relationship between indices and elements. This relationship is called a mapping; each index “maps to” one of the elements.
List indices work the same way as string indices:
Any integer expression can be used as an index.
If you try to read or write an element that does not exist, you get an
IndexError
.If an index has a negative value, it counts backward from the end of the list.
The in
operator also works on lists.
- [4, 2, True, 8, 6, 5]
- Item assignment does not insert the new item into the list.
- [4, 2, True, 6, 5]
- Yes, the value True is placed in the list at index 2. It replaces 8.
- Error, it is illegal to assign
- Item assignment is allowed with lists. Lists are mutable.
Q-3: What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
alist[2] = True
print(alist)
- [3, 2, 1]
- That is the original contents of
values
, but the contents are changed. - [2, 0, 2]
- When you set
values[0]
tovalues[1]
it makes a copy of the value and doesn't zero it out. - [2, 2, 2]
- The value at index 0 is set to a copy of the value at index 1 and the value at index 2 is incremented.
- [2, 2, 1]
- Notice that we do change the value at index 2. It is incremented by 1.
Q-4: What would the following code print?
values = [3, 2, 1]
values[0] = values[1]
values[2] = values[2] + 1
print(values)
- True
- in returns True for top level items only. 57 is in a sublist.
- False
- Yes, 57 is not a top level item in alist. It is in a sublist.
Q-5: What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(57 in alist)