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

Swapping elements in a list in Python

I am trying to swap the elements of list A i.e. (i,j) turns to (j,-i). But there is an error.

A=[(0,0),(0,1),(1,0),(1,1)]

for i in range(0,len(A)-1):
    for j in range(0,len(A)-1):
        A[i][j]=A[j][-i]

The error is

in <module>
    A[i][j]=A[j][-i]

TypeError: 'tuple' object does not support item assignment

The expected output is

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

[(0,0),(1,0),(0,-1),(-1,-1)]

>Solution :

What you have is a list of tuples, and tuples are immutable. What you’re doing would not be described so much as "swapping elements in a list" as swapping the elements of a tuple (and negating the second one).

If you have

a = (1, 1)

then you could perform this operation like:

b = (a[1], -a[0])

Performing that over a list of items a separate level of abstraction that can be handled in many different ways. For example using a list comprehension:

A = [(0, 0), (0, 1), (1, 0), (1, 1)]
B = [(a[1], -a[0]) for a in A]

or more simply using tuple unpacking:

B = [(j, -i) for i, j in A]
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