31

Following on my previous question How to group list items into tuple?

If I have a list of tuples, for example

a = [(1,3),(5,4)]

How can I unpack the tuples and reformat it into one single list

b = [1,3,5,4]

I think this also has to do with the iter function, but I really don't know how to do this. Please enlighten me.

Community
  • 1
  • 1
LWZ
  • 11,670
  • 22
  • 61
  • 79

5 Answers5

67
b = [i for sub in a for i in sub]

That will do the trick.

Volatility
  • 31,232
  • 10
  • 80
  • 89
  • 6
    oh yeah, that was easy, what was I thinking... – LWZ Mar 07 '13 at 10:55
  • 1
    Nice one. I had to think about it for a second - _"where did sub come from at the end?"_ – bjd2385 Nov 08 '16 at 21:05
  • 1
    Why/how does this work? – ruief Nov 10 '17 at 23:12
  • 3
    Please explain how that works, I am also confused by the double loop – Asara Nov 29 '17 at 12:30
  • 4
    @ruief @Asara the double loop works exactly as if you wrote it out as a nested for-loop: `for sub in a` picks out each sublist (or in this case, each tuple) of `a`, and then `for i in sub` picks out each element in each sublist, which is put together to form the resultant list. Hope that makes it a bit clearer. – Volatility Nov 29 '17 at 20:49
  • 1
    Didn't know you could double loop in a list comp, nice. Answer works and is concise so have upvoted... but damn that syntax is hard to read. – otocan Sep 14 '21 at 13:54
14
In [11]: list(itertools.chain(*a))
Out[11]: [1, 3, 5, 4]

If you just need to iterate over 1, 3, 5, 4, you can get rid of the list() call.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

Just iterate over the list a and unpack the tuples:

l = []
for x,y in a:
   l.append(x)
   l.append(y)
Schuh
  • 1,045
  • 5
  • 9
3

Another way:

a = [(1,3),(5,4)]
b = []

for i in a:
    for j in i:
        b.append(j)

print b

This will only handle the tuples inside the list (a) tho. You need to add if-else statements if you want to parse in loose variables too, like;

a = [(1,3),(5,4), 23, [21, 22], {'somevalue'}]
b = []

for i in a:
    if type(i) == (tuple) or type(i) == (list) or type(i) == (set):
        for j in i:
            b.append(j)
    else:
        b.append(i)

print b
  • Use `isinstance(i, collections.Iterable)` instead of the type checking (assuming `collections` has already been imported) – Volatility Mar 07 '13 at 11:15
1
import itertools
b = [i for i in itertools.chain(*[(1,3),(5,4)])]
danodonovan
  • 19,636
  • 10
  • 70
  • 78