Home > Enterprise >  Assigning to slices in Python reversed list
Assigning to slices in Python reversed list

Time:12-28

I'm reading the "Fluent Python" book and a section talks about assigning to slices. For example:

l = list(range(10))
l[2:5] = [20, 30]
#l is [0, 1, 20, 30, 5, 6, 7, 8, 9]

I tried testing this feature with some customised examples, but the following gives me an error:

l = list(range(10))
l[::-1] = [10, 1] #ValueError: attempt to assign sequence of size 2 to extended slice of size 10
print(l)

but this works:

l = list(range(10))
l = l[::-1]
l[:] = [10, 1]
print(l) #[10, 1]

Why am I getting the error? Isn't what I'm trying to do the same as the last cell?

Thanks

CodePudding user response:

When you use a step other than 1 (e.g. l[::-1], l[2:20:3]), the subscript corresponds to a list of specific element indexes so you need to provide the same number of elements.

When you don't specify a step (or a step of 1), the subscript corresponds to a contiguous range of elements in the list so it can be replaced with a different number of elements.

  • Related