Chapters
Python114 chapters

CollectionsChapter 26 of 114

Change Items

Replace one item or a whole slice, in place.

Assign to a position

A list is mutable, so you can assign straight to an index:

Python
names = ["Ada", "Grace", "Katherine"]
names[1] = "Alan"
print(names)

Output

['Ada', 'Alan', 'Katherine']

The list is changed in place. Every name pointing at it sees the new value, which is the behaviour that makes lists useful and occasionally surprising.

Python
a = [1, 2, 3]
b = a
a[0] = 99
print(b)

Output

[99, 2, 3]

The position has to exist

Assigning past the end is an error, not an extension:

Python
names = ["Ada"]
try:
    names[5] = "Grace"
except IndexError as problem:
    print("IndexError:", problem)

Output

IndexError: list assignment index out of range

To make the list longer, use append() or insert(), which the next chapter covers.

Assign to a slice

Assigning to a slice replaces that whole stretch. The replacement does not have to be the same length:

Python
numbers = [1, 2, 3, 4, 5]
numbers[1:3] = ["a", "b", "c"]
print(numbers)

Output

[1, 'a', 'b', 'c', 4, 5]

Two items came out and three went in, so the list grew.

Deleting with a slice

An empty replacement removes the stretch:

Python
numbers = [1, 2, 3, 4, 5]
numbers[1:3] = []
print(numbers)

Output

[1, 4, 5]

Replacing everything

[:] is the whole list, so assigning to it swaps the contents while keeping the same object:

Python
a = [1, 2, 3]
b = a
a[:] = [7, 8]
print(a)
print(b)

Output

[7, 8]
[7, 8]

Compare that with a = [7, 8], which points a at a new list and leaves b looking at the old one:

Python
a = [1, 2, 3]
b = a
a = [7, 8]
print(a)
print(b)

Output

[7, 8]
[1, 2, 3]

Changing while looping

Removing items from a list while looping over it skips things, because the positions shift underneath you:

Python
numbers = [1, 2, 3, 4]
for n in numbers:
    if n % 2 == 0:
        numbers.remove(n)
print(numbers)

Output

[1, 3]

That one happens to look right. Change the data and it stops being right:

Python
numbers = [2, 4, 6]
for n in numbers:
    if n % 2 == 0:
        numbers.remove(n)
print(numbers)

Output

[4]

Build a new list instead, which the comprehension chapter makes short work of:

Python
numbers = [2, 4, 6]
numbers = [n for n in numbers if n % 2 != 0]
print(numbers)

Output

[]

Test yourself

2 questions

After a = [1, 2, 3]; b = a; a[0] = 99, what is b?

Show the answer

[99, 2, 3] — One list with two names. Changing it through either name shows through both.

What is the difference between a[:] = [7, 8] and a = [7, 8]?

Show the answer

The first replaces the contents of the same list; the second points a at a new one — That difference decides whether other names pointing at the old list see the change.

Next chapter

Add Items

append, insert and extend, and the difference between them.