Home > Software engineering >  removing tuples in a list to form a single list python
removing tuples in a list to form a single list python

Time:12-07

I have a list that contains 2 tuples:

oldlist = [('10', '11', '12', '13',), ('apple', 'banana', 'pear', 'orange')]

I would like to find out if is there is a way that I can convert this back into a single list only:

newlist = ['10,apple', '11,banana', '12,pear', '13,orange']

I previously used zip to achieve oldlist and was wondering if there's a trick that can work for the reverse. Many thanks!

CodePudding user response:

If you want exactly your output (strings) you can use the answer of flakes in the comments:

list(map(','.join, zip(*oldlist)))

If you want tuples as an output:

[('10', 'apple'), ('11', 'banana'), ('12', 'pear'), ('13', 'orange')]

You can simply use zip again:

Python 2:

zip(*oldlist)

Python 3

[*zip(*oldlist)]

  • Related