Home > database >  Python swap elements between two tuples of two ints
Python swap elements between two tuples of two ints

Time:10-07

The problem is: swapping the second element between two tuples meeting all the following criteria: consisting of two ints, each in range(5), elements in same positions aren't equal

If they are two lists I can simply use variable swapping with indexing but tuples are immutable so I unpacked the two tuples into a single list and unpacked that list into four variables and reordered the variables...

Example Code

(See the initial values the variables are declared with, the printed values are the intended result.)

a, b = [1,2], [3,4]      
a[1], b[1] = b[1], a[1]  
print(a)                 
print(b)                 
                         
l1, l2 = (1,2), (3,4)    
a, b, c, d = [*l1, *l2]  
print((a, d))            
print((c, b))            
In [161]: a, b = [1,2], [3,4]
     ...: a[1], b[1] = b[1], a[1]
     ...: print(a)
     ...: print(b)
     ...:
     ...: l1, l2 = (1,2), (3,4)
     ...: a, b, c, d = [*l1, *l2]
     ...: print((a, d))
     ...: print((c, b))
[1, 4]
[3, 2]
(1, 4)
(3, 2)

I don't want to cast the tuples into lists, I wonder if there is a better way to swap the second element between the two tuples?

CodePudding user response:

You're right that the tuples are immutable, and you won't be able to get around creating new tuples. If you just want to do this without using unpacking notation, you could do something like

l1, l2 = (1,2), (3,4)
a = (l1[0],l2[1])
b = (l2[0],l1[1])

If speed is a concern here, running this with pypy will be very efficient.

CodePudding user response:

Try this:

t = (1, 2)

swapped = t[::-1]

# true
assert type(swapped) == tuple
assert swapped == (2, 1)
  • Related