2

I have a list s which looks as below:

s = list(range(1, 11))

I am replacing slice of 's' using below code:

s[1:4] = [0, 0, 0, 0]
print(s)

Output: [1, 0, 0, 0, 0, 5, 6, 7, 8, 9, 10]

However, when trying to assign the same list [0, 0, 0, 0] to an extended slice of 's', then the interpreter is throwing an error.

s[1:4:2] = [0, 0, 0, 0]

ValueError: attempt to assign sequence of size 4 to extended slice of size 2

I want to understand why python didn't throw an error with s[1:4] = [0, 0, 0, 0] because even in that case we are attempting to assign sequence of size 4 to slice of size 3?

meallhour
  • 13,921
  • 21
  • 60
  • 117
  • What is the expected result with using the slice option `[1:4:2]` ? –  Mar 20 '22 at 21:42
  • 1
    The error is telling you exactly what's wrong: `s[1:4:2]` is equivalent to `[2, 4]`. How can you assign `[0, 0, 0, 0]` to those two spots? – Mark Mar 20 '22 at 21:44
  • I have updated my question. please have a look. thanks! – meallhour Mar 20 '22 at 21:45
  • 1
    If you look [here](https://docs.python.org/3/library/stdtypes.html?highlight=cached_property#sequence-types-list-tuple-range): `s[i:j:k] = t` means _the elements of `s[i:j:k]` are replaced by those of t_, and _t must have the same length as the slice it is replacing_. There's no length requirement in the case of `s[i:j] = t`: _slice of s from i to j is replaced by the contents of the iterable t_. – Timus Mar 20 '22 at 22:43

1 Answers1

0

I want to understand why python didn't throw an error with s[1:4] = [0, 0, 0, 0] because even in that case we are attempting to assign sequence of size 4 to slice of size 3?

Let's even take a more "hardcore example"

s = list(range(1, 11))
s[1:2] = [0,0,0,0,0,0,0]
print(s)

What is exactly done here is:

  1. Take s[1:2] elements, in this case it's only the value 2.
  2. Place elements into this spot, as in replace values between index 1 and 2 with corresponding values.

While you are trying to apply it to s[1:4:2] so values 2 and 4, you are trying to do what you were saying, as in:

Assign sequence of size 4 to slice of size 3

Which clearly can't be done. Also, coming back to the first example, check also the same thing with s[1:1], s[1] and you will find funny examples of this thing.