nvergos nvergos - 2 months ago 6
Python Question

Access all elements of nested lists

I am trying to find a short and elegant way in order to access all individual elements in nested lists. For example:

lst1 = ['1', '2', '3']
lst2 = ['4', '5']

outer = [lst1, lst2]


Is there a list comprehension that would return
['1', '2', '3', '4', '5']
?

Answer

There are two short similar ways to do it:

import itertools

# with unpacking
list(itertools.chain(*outer))  

# without unpacking
list(itertools.chain.from_iterable(outer))