python – How to extract all elements from a list of lists in a one-liner (without using modules)?

Question:

I have a list of lists:

arr = [[1, 2], [3, 4], [1, 4]]

It is necessary to get all the elements (numbers) from the given construction.

Implemented in the forehead:

res = []
for obj in arr:
    res += [elem for elem in obj]

But I want a one-line solution.

Tell me, is it possible to implement it by standard means (without additional libraries)?

I went through several options until I found anything.


PS: I found such a "perversion", but this is still a godless "perversion", and not a beautiful solution:

res = list(map(int, ' '.join(f"{obj[0]} {obj[1]}" for obj in arr).split()))

Answer:

Use the sum (…, start = []) parameter :

res = sum(arr, [])

result:

In [4]: res
Out[4]: [1, 2, 3, 4, 1, 4]

But the most idiomatic solution in this case would be to use itertools.chain . There is even a mention of this in the docstring by the built-in function sum() :

To concatenate a series of iterables, consider using itertools.chain ().

from itertools import chain

res = list(chain.from_iterable(arr))

UPDATE: comparing the execution speed of different solutions:

In [9]: %timeit sum([list(range(1000))]*1000, [])
2.25 s ± 69.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [10]: %timeit [x for xs in [list(range(1000))]*1000 for x in xs]
27.9 ms ± 428 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [11]: %timeit list(chain.from_iterable([list(range(1000))]*1000))
11.8 ms ± 266 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Scroll to Top