You can assign to a whole section of a list at once by targeting a slice:
items = [0, 0, 0, 0, 0]
items[1:4] = [10, 20, 30]
print(items) # [0, 10, 20, 30, 0]The left side selects positions; the right side supplies values. Everything below follows from that.
Replacing a section#
letters = ["a", "b", "c", "d", "e"]
letters[1:3] = ["X", "Y"] # same length
print(letters) # ['a', 'X', 'Y', 'd', 'e']Unlike a fixed-size array, the lengths do not have to match — the list resizes itself:
letters = ["a", "b", "c", "d", "e"]
letters[1:3] = ["X"] # two positions, one value
print(letters) # ['a', 'X', 'd', 'e'] — list shrank
letters[1:2] = ["P", "Q", "R"] # one position, three values
print(letters) # ['a', 'P', 'Q', 'R', 'd', 'e'] — grewSetting every position#
items = [0] * 5
items[:] = [9] * 5 # replace contents, keep the same list object
print(items) # [9, 9, 9, 9, 9]
# Every other position
items[::2] = [1, 1, 1]
print(items) # [1, 9, 1, 9, 1]items[:] = ... is worth knowing: it replaces the contents in place, so any other name pointing at the same list sees the change. items = [...] would just rebind the name.
Inserting without replacing#
items = ["a", "d"]
items[1:1] = ["b", "c"] # zero-width slice = pure insertion
print(items) # ['a', 'b', 'c', 'd']A slice where start and end are equal selects nothing, so the assignment inserts at that point.
Deleting a section#
items = ["a", "b", "c", "d"]
items[1:3] = [] # assign an empty list
del items[1:3] # or use del — clearer
print(items) # ['a', 'd']The other trap: strings are sequences#
items = [1, 2, 3]
items[0:1] = "abc"
print(items) # ['a', 'b', 'c', 2, 3] — split into characters!
items = [1, 2, 3]
items[0:1] = ["abc"] # wrap it
print(items) # ['abc', 2, 3]Slice assignment iterates whatever you give it. A string iterates one character at a time, which is almost never what you meant.
Assigning a non-iterable fails outright:
items[0:1] = 5
# TypeError: can only assign an iterableBuilding a fixed-size list first#
results = [None] * 10 # ten placeholders
for i, value in enumerate(source):
results[i] = transform(value)Questions people ask#
Why does items[5] = x fail on an empty list?
Index assignment only replaces an existing position. To grow the list use append, or create it at the size you need with [None] * n.
What is the difference between items[:] = x and items = x?
The first replaces the contents of the existing list; the second points the name at a new list. It matters when another variable refers to the same list.
Can I do this with tuples?
No — tuples cannot be changed after creation. Convert to a list, modify, convert back.