1

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']?

nvergos
  • 432
  • 3
  • 15
  • 4
    `outer = lst1 + lst2` – lycuid Oct 04 '16 at 17:01
  • 5
    See [Making a flat list out of list of lists in Python](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python). I think that's what you're asking – roganjosh Oct 04 '16 at 17:03
  • Are you interested in arbitrarily nested lists, or only those nested to a single degree (as your example is)? For flattening arbitrarily-deep structures, see http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html – Robᵩ Oct 04 '16 at 17:08
  • Thank you all, I am looking into arbitrarily nested lists, trying to minimize the number of costly for loops. Flattening is more along the lines of what I'm interested in. – nvergos Oct 04 '16 at 17:10
  • In Python 2.7 you can also use `from compiler.ast import flatten` and then just call `flatten()` on a nested list. That also leads to [Python 3 replacement for deprecated compiler.ast flatten function](http://stackoverflow.com/questions/16176742/python-3-replacement-for-deprecated-compiler-ast-flatten-function) which might be of interest. There seem to be lots of ways to do it, not sure why `from compiler.ast import flatten` was deprecated as I never tested efficiency – roganjosh Oct 04 '16 at 17:13

2 Answers2

0
import itertools

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

flattened = list(itertools.chain(*outer))
['1', '2', '3', '4', '5']
JoshuaBox
  • 735
  • 1
  • 4
  • 16
0

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))
Artem Selivanov
  • 1,867
  • 1
  • 27
  • 45