Skip to content
Happy Programming Guide
Start learning
Python

Setting a Sequence of List Elements in Python

Assigning to a slice, filling a range of positions, replacing a section with a different number of items, and the shape errors that come with it.

Lines of source code on a dark computer screen

You can assign to a whole section of a list at once by targeting a slice:

Python
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#

Python
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:

Python
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']  — grew

Setting every position#

Python
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#

Python
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#

Python
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#

Python
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:

Python
items[0:1] = 5
# TypeError: can only assign an iterable

Building a fixed-size list first#

Python
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.

Where to go next#

Next lessonPython lists explained

Keep reading

Python

Handling Warnings in Python

What Python warnings mean, how to see them all, silence the ones you have decided about, and turn the dangerous ones into…

3 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *