0

Possible Duplicate:
Making a flat list out of list of lists in Python

how can I create form a list e.g [[1,2],[3,4]] or [(1,2),(3,4)] the list [1,2,3,4]

list comprehension(or map, filter)doesn't seems to have map object to more than one other object.

like SelectMany in C#'s LINQ

Community
  • 1
  • 1
Alon Gutman
  • 865
  • 2
  • 14
  • 22

4 Answers4

2

Standard libs are cool:

>>> import itertools
>>> l = [[1,2],[3,4]]
>>> list(itertools.chain(*l))
[1, 2, 3, 4]
Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75
0

You want to flatten the list.

[y for x in [[1,2],[3,4]] for y in x]
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
0

Provided you know that it will be exactly 2 levels deep, you can do

[j for i in [[1,2],[3,4]] for j in i]

where you iterate with i over the list, giving i successively the values [1,2] and [3,4], and with j over these sub-lists. Thus this expression results to [1, 2, 3, 4].

glglgl
  • 89,107
  • 13
  • 149
  • 217
0
>>l=[1,2,3,4]
>>zip(l[:2:],l[1:][:2:])
[(1, 2), (2, 3)]

>>l=[(1, 2), (2, 3)]
>>sum(l,())
(1, 2, 2, 3)

It's not just what you need?

Arty
  • 579
  • 1
  • 8
  • 17