0

What the beat way to convert:

[(1, 2), (3, 4)] => [1, 2, 3, 4]

I tried

[i for i in row for row in [(1, 2), (3, 4)]]

but it's not work.

Xiaorong Liao
  • 1,201
  • 14
  • 14
  • 1
    Yes, it's a dumplicate question in some kind. I just can't find it(I don't know how to expression this question). Thanks for your mention. – Xiaorong Liao Dec 04 '15 at 06:25

3 Answers3

2

You can do this also with chain from itertools

from itertools import chain
a = [(1, 2), (3, 4)]
print(list(chain.from_iterable(a)))

>>>>[1, 2, 3, 4]
JDurstberger
  • 4,127
  • 8
  • 31
  • 68
1

A list comprehension is the best way to do this

>>> L = [(1, 2), (3, 4)]
>>> [j for i in L for j in i]
[1, 2, 3, 4]

Note that the "outer loop" variable needs to come first

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1
>>> [i for row in [(1, 2), (3, 4)] for i in row]
[1, 2, 3, 4]
>>> 

[i for row in [(1, 2), (3, 4)] for i in row]
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^  # you need define 'row' before define 'i'
Remi Guan
  • 21,506
  • 17
  • 64
  • 87