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
[(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]