Given the tuples : tuple1 = (3,5,16,35,75) and tuple2 = (1,19,28,44,64), I would like the output to be list5=[3, 1, 5, 19, 16, 28, 35, 44, 75, 64]. This is what I've done but I know this isn't the best way to do it.
list5 =[]
list5.append(tuple1[0])
list5.append(tuple2[0])
list5.append(tuple1[1])
list5.append(tuple2[1])
list5.append(tuple1[2])
list5.append(tuple1[3])
list5.append(tuple2[3])
list5.append(tuple1[4])
list5.append(tuple2[4])
print(list5)
CodePudding user response:
You can zip
the two tuples then create a single list using a list comprehension.
>>> tuple1 = (3,5,16,35,75)
>>> tuple2 = (1,19,28,44,64)
>>> [i for j in zip(tuple1, tuple2) for i in j]
[3, 1, 5, 19, 16, 28, 35, 44, 75, 64]
If there is a chance the tuples are of uneven length you can use itertools.zip_longest
instead of zip
>>> from itertools import zip_longest
>>> tuple1 = (3,5,16,35,75)
>>> tuple2 = (1,19,28,44,64,89,101)
>>> [i for j in zip_longest(tuple1, tuple2) for i in j if i is not None]
[3, 1, 5, 19, 16, 28, 35, 44, 75, 64, 89, 101]
CodePudding user response:
You can use itertools
and zip
to support tuples of arbitrary size -
list5 = list(itertools.chain(*[[t1, t2] for t1, t2 in zip(tuple1, tuple2)]))
Update
Following the comments I think -
list(chain(*zip(tuple1, tuple2)))
is the most elegant way
CodePudding user response:
Using zip() is a common way to approach this but if one of the tuples is longer than the other, you'll need a bit of extra work:
tuple1 = (3,5,16,35,75,98,99,100)
tuple2 = (1,19,28,44,64)
list5 = [n for z in zip(tuple1,tuple2) for n in z] # alternate values
list5 = [*tuple1[len(tuple2):],*tuple2[len(tuple1):]] # longer tuple
print(list5)
[3, 1, 5, 19, 16, 28, 35, 44, 75, 64, 98, 99, 100]
It possible to do it without using zip, but it's a bit more convoluted:
list5 = [t[i] for i in range(max(len(tuple1),len(tuple2)))
for t in (tuple1,tuple2) if i<len(t)]