Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

change odd elements in list to negative

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading