zoe
zoe

Reputation: 311

Create single tuple from two tuples python3

I'm a newbie at python and want to create a single tuple from two tuples such that the order of the two tuples is maintained eg the result should be:

final_tup =  ((75, 57), (77, 6), (55, 64), (93, 36), (41, 63), (62, 53), (70, 26), (30, 71), (74, 88), (97, 66))

x = (75, 77, 55, 93, 41, 62, 70, 30, 74, 97)
y = (57, 6, 64, 36, 63, 53, 26, 71, 88, 66)

I am nearly there but I can't seem to get the final tuple out. I have:

tup = zip()
x = (75, 77, 55, 93, 41, 62, 70, 30, 74, 97)
y = (57, 6, 64, 36, 63, 53, 26, 71, 88, 66)
lx = list(x)
ly = list(y)
tup = zip(lx, ly)
for value in tup:
    print(value)

Also I'm sure there is a more elegant way in python without having to convert to a list

Upvotes: 0

Views: 616

Answers (1)

Kevin Fang
Kevin Fang

Reputation: 2012

Actually you are pretty close. Try this:

final_tuple = tuple(zip(x,y))
Out[3]: 
((75, 57),
 (77, 6),
 (55, 64),
 (93, 36),
 (41, 63),
 (62, 53),
 (70, 26),
 (30, 71),
 (74, 88),
 (97, 66))

Explanation:

zip method can take any iterable argument including tuples, so you don't have to make it a list first. It returns an iterator of zipped tuples, in order to get tuple of tuples, you have to use tuple method on that iterator.

Upvotes: 4

Related Questions