Change a List Item by Index
To change a list item by index, assign to it: seats[1] = "A" puts
"A" in place of the item at index 1. The list keeps its length.
Before this lesson you should know how to make a list and read an item by its index: see Lists.
Replace one item
Indexes start at 0, so seats[1] is the second item:
seats = ["-", "-", "-"]seats[1] = "A"print(seats)It printed ['-', 'A', '-']. The "-" in the second place is gone, and
"A" sits in its place.
The list changes, but keeps its length
The assignment changes the list itself. Print it before and after to see the same list with one new item:
seats = ["-", "-", "-", "-"]print(seats)seats[0] = "B"print(seats)print(len(seats))Both lines show four seats, and len() still gives 4. .append() would add
a fifth item instead; an index assignment never adds one.
Use a typed number as the index
input() gives back text, such as "2", and an index must be a whole number.
Convert the answer with int(), then use the variable as the index:
seats = ["-", "-", "-", "-"]seat = int(input("Which seat do you want? "))seats[seat] = "C"print(seats)Run it and type 2. It prints ['-', '-', 'C', '-']. Without int(),
seats["2"] raises a TypeError.
The index must be inside the list
You can only replace an item that exists. The last index is one less than
len():
seats = ["-", "-", "-"]seats[2] = "D"print(seats)seats[3] = "E" # this line raises IndexError: there is no fourth seatNote: a string cannot be changed this way. word[0] = "C" raises a
TypeError, because strings are immutable.
See also: Lists, Reading Input.
Your turn
Change the last item of flags to "F", then print the list.
['-', '-', 'F']
flags = ["-", "-", "-"]# change the last item to "F", then print flags