Python List Slice Assignment Guide – Python Tutorial

By | June 4, 2024

In this tutorial, we will introduce how to assign value for list slice. It is a simple tutorial.

For example:

x = [1,2,3,4,5,6]
x[2:5] = 4

Run this code, we will see:

TypeError: can only assign an iterable

How to assign value for list slice?

We should use a list to assign for a list slice.

For example:

x[2:5] = [0, 1, 3]

We will get:

[1, 2, 0, 1, 3, 6]

In this example:

x[2:5], it contains 3 elements. Then we can assign new value using a new list that contains 3 elements.

However, if we use a small or large list to assign. What will happen?

For example:

x[2:5]= [1]

We will get:

[1, 2, 1, 6]

More example:

x[1:2] = [0,0,0,0,1,2,3]

We will get:

[1, 0, 0, 0, 0, 1, 2, 3, 1, 6]

Leave a Reply