2

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?

Thyebri
  • 579
  • 1
  • 17

2 Answers2

3

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.

eeegnu
  • 396
  • 1
  • 10
0

Try this:

t = (1, 2)

swapped = t[::-1]

# true
assert type(swapped) == tuple
assert swapped == (2, 1)
rv.kvetch
  • 5,465
  • 3
  • 10
  • 28
  • You aren't reading through my question – Thyebri Oct 07 '21 at 02:58
  • It's a lot to read.. – rv.kvetch Oct 07 '21 at 02:58
  • I have posted example codes explaining what exactly I want, and you method doesn't give that result. – Thyebri Oct 07 '21 at 03:00
  • To be honest (and don't take this the wrong way) but you could probably remove a lot of unnecessary info from your question. For example, the first 3 paragraphs could probably be removed. It would be helpful if you could provide an [MRE](https://stackoverflow.com/help/minimal-reproducible-example) elaborating on the problem you are having. – rv.kvetch Oct 07 '21 at 03:01