change odd elements in list to negative
Question:
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
Answers:
Best way would be to do it vectorized with numpy. Without numpy, I don’t see a way to do it without creating a new loop. Here you have two examples of how to do it. With and without numpy:
import numpy as np
# vectorized
a = np.arange(10)
a[1::2] *= -1
print(a)
# >>> [ 0 -1 2 -3 4 -5 6 -7 8 -9]
a = [i for i in range(10)]
a = [i if i%2==0 else i*-1 for i in a] # need to loop through list again..
print(a)
# >>> [0, -1, 2, -3, 4, -5, 6, -7, 8, -9]
Edited to fix odd elements to negative, not pos.
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.
You can fix it like this:
mylist[1::2] = [-i for i in mylist[1::2]]
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
Best way would be to do it vectorized with numpy. Without numpy, I don’t see a way to do it without creating a new loop. Here you have two examples of how to do it. With and without numpy:
import numpy as np
# vectorized
a = np.arange(10)
a[1::2] *= -1
print(a)
# >>> [ 0 -1 2 -3 4 -5 6 -7 8 -9]
a = [i for i in range(10)]
a = [i if i%2==0 else i*-1 for i in a] # need to loop through list again..
print(a)
# >>> [0, -1, 2, -3, 4, -5, 6, -7, 8, -9]
Edited to fix odd elements to negative, not pos.
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.
You can fix it like this:
mylist[1::2] = [-i for i in mylist[1::2]]