Pregunta

This is python syntax related question... Is there more elegant and more pythonic way of doing this:

>>> test = [[1,2], [3,4,5], [1,2,3,4,5,6]]
>>> result = []
>>> for i in test: result += i
>>> result
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6]

Join multiple list (stored inside another list) to one long list?

¿Fue útil?

Solución

Use the itertools.chain.from_iterable() classmethod:

from itertools import chain

result = list(chain.from_iterable(test))

If all you need to do is iterate over the chained lists, then don't materialize it to a list(), just loop:

for elem in chain.from_iterable(test):
    print(elem, end=' ')   # prints 1 2 3 4 5 1 2 3 4 5 6

You can also use parameter unpacking, directly on itertools.chain:

for elem in chain(*test):

But do this only with a smaller list.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top