-1

Is there a simple function that can extract all numbers from a list of lists. For example:

l = [ [1,2], [1, 5], [2] ] -> [1,2,1,5,2]

i would like to avoid using loops or list comprehensions.

GpG
  • 502
  • 5
  • 11
  • 1
    this operation is called _list flattening_. Google it. – xrisk May 22 '18 at 11:28
  • Do all of the inner lists contain just numbers? If so, this is a definite duplicate. If not, a layer of filtering needs to be added. Also, why would you want to avoid a list comprehension when constructing a list? It is the most pythonic solution. – John Coleman May 22 '18 at 11:31

3 Answers3

2

I would like to avoid using loops or list comprehensions.

You can use itertools.chain method in combination with Extended iterable unpacking operator.

chain method makes an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.

import itertools
merged = list(itertools.chain(*l))

Output

[1,2,1,5,2]

Another approach is to use reduce function.

l = reduce(lambda x,y: x+y,l)
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1

Use list comprehension:

>>> x = [j for i in l for j in i]
[1, 2, 1, 5, 2]
akash karothiya
  • 5,736
  • 1
  • 19
  • 29
1

Using itertools.chain

Demo:

import itertools
l = [ [1,2], [1, 5], [2] ] 
print(list(itertools.chain(*l))) #or print(list(itertools.chain.from_iterable(l)))

Output:

[1, 2, 1, 5, 2]
Rakesh
  • 81,458
  • 17
  • 76
  • 113