1

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

4
  • 2
    What you are trying to do is the same; how you are trying to do it is different. Commented Dec 26, 2021 at 3:03
  • Yeah makes sense! I'm reversing the list in the first example and doing the assignment at the same time, but in the second example, the list is first reversed, and then new items are assigned to the list Commented Dec 26, 2021 at 3:05
  • 1
    In your second example, the fact that l was (re)defined using a negative step size is irrelevant to the subsequent assignment. Commented Dec 26, 2021 at 21:32
  • 1
    The documentation for slice assignments appears to be silent on the question of how to interpret a step size other than the default. Commented Dec 26, 2021 at 21:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow great point. Thanks a lot!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.