Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unnest a nested list [duplicate]

Tags:

python

Possible Duplicate:
Making a flat list out of list of lists in Python

I am trying to find an easy way to turn a multi dimensional (nested) python list into a single list, that contains all the elements of sub lists.

For example:

A = [[1,2,3,4,5]] 

turns to

A = [1,2,3,4,5] 

or

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

turns to

A = [1,2,3,4] 
like image 653
codious Avatar asked Aug 08 '12 08:08

codious


People also ask

How do I undo a nested list in Python?

Flatten the list to "remove the brackets" using a nested list comprehension. This will un-nest each list stored in your list of lists!

How do I flatten a list of lists?

Flatten List of Lists Using itertools (chain()) This approach is ideal for transforming a 2-D list into a single flat list as it treats consecutive sequences as a single sequence by iterating through the iterable passed as the argument in a sequential manner.


1 Answers

Use itertools.chain:

itertools.chain(*iterables):

Make 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. Used for treating consecutive sequences as a single sequence.

Example:

from itertools import chain  A = [[1,2], [3,4]]  print list(chain(*A)) # or better: (available since Python 2.6) print list(chain.from_iterable(A)) 

The output is:

[1, 2, 3, 4] [1, 2, 3, 4] 
like image 158
moooeeeep Avatar answered Sep 20 '22 04:09

moooeeeep