I am trying to change odd elements in a list of int to negative using slicing
l[1::2] = -1 * l[1::2]
However, I encounter the following error:
ValueError: attempt to assign sequence of size 0 to extended slice of size 2
>Solution :
If you wish to uses slices:
>>> a = [1,4,7,8,2]
>>> a[1::2] = [-x for x in a[1::2]]
>>> a
[1, -4, 7, -8, 2]
When assigning to an extended slice like a[1::2], the list/slice on the right hand side must be the same length as the left hand side. In the above, we’ve mapped to a[1::2] with a list comprehension, so the length is unchanged. If we consider -1 * a[1::2] this yields [] which is of a different length.