1

I have:

mylist = [(['a', 'b'], [1, 2]), (['c', 'd'], [3])]

I need one list with the letters and one with the numbers, like this:

(['a', 'b', 'c', 'd'], [1, 2, 3])

I have made some efforts, but I could just get one list with the letters, not both:

answer = [item for sublist in mylist for item in sublist[0]]
#returns ['a', 'b', 'c', 'd']
1
  • 5
    answer = [[item for sublist in mylist for item in sublist[i]] for i in range(2)]
    – Max
    Commented Apr 27, 2019 at 13:51

3 Answers 3

6

answer = [[item for sublist in mylist for item in sublist[i]] for i in range(2)]

Just need to iterate through your sublist :)

3

Here's a simple alternative using zip and itertools.chain:

from itertools import chain
[list(chain.from_iterable(i)) for i in zip(*mylist)]
# [['a', 'b', 'c', 'd'], [1, 2, 3]]
3
  • 1
    chain is nice... alternatively you could avoid it and just use a nested list-comp, eg: [[a for b in el for a in b] for el in zip(*mylist)] Commented Apr 27, 2019 at 14:57
  • Yes there's always the list-comp alternative to flatten lists @JonClements, chain is nice though for conciseness and performance
    – yatu
    Commented Apr 27, 2019 at 15:02
  • Indeed... in terms of efficiency though, you probably want to go for chain.from_iterable(i) instead of chain(*i) as it exists exactly for that case (and imho is even more explicit than unpacking) Commented Apr 27, 2019 at 15:03
2

zip works as well:

tuple(map(lambda x: x[0]+x[1],  zip(mylist[0], mylist[1])))

Code:

mylist = [(['a', 'b'], [1, 2]), (['c', 'd'], [3])]

print(tuple(map(lambda x: x[0]+x[1],  zip(mylist[0], mylist[1]))))
# (['a', 'b', 'c', 'd'], [1, 2, 3])

Not the answer you're looking for? Browse other questions tagged or ask your own question.