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,011
  • 13
  • 13
  • 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
  • 3,987
  • 5
  • 29
  • 63
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
  • 281,034
  • 50
  • 354
  • 495
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
  • 20,142
  • 17
  • 60
  • 81