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

Invert indices of two lists in Python

I need to compare two lists (list1 and list2) on sign changes and I want to invert those indices in the second list that undergo sign changes. This means that I want to change the -4 and the -11 in list2 to 4 and 11. How can I do this?

list1 = [1,4,5,6,8,10]
list2 = [3,10,-4,7,-11,10]

>Solution :

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

If I understand your question correctly, then you can do this fairly straightforward with list comprehension:

list3 = [j*-1 if (i < 0 and j > 0) or (i > 0 and j < 0) else j for i, j in zip(list1, list2)]

print(list3)

[3, 10, 4, 7, 11, 10]
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