Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to flatten arbitrarily nested lists in Python? [duplicate]

Possible Duplicate:
Flattening a shallow list in Python
Flatten (an irregular) list of lists in Python

EDIT: The question is not how to do it - this has been discussed in other questions - the question is, which is the fastest method?

I've found solutions before, but I'm wondering what the fastest solution is to flatten lists which contain other lists of arbitrary length.

For example:

[1, 2, [3, 4, [5],[]], [6]] 

Would become:

[1,2,3,4,5,6] 

There can be infinitely many levels. Some of the list objects can be strings, which mustn't be flattened into their sequential characters in the output list.

like image 252
Ivy Avatar asked May 30 '12 20:05

Ivy


People also ask

How do you flatten a nested list in Python?

Provide two arguments to the sum() method: my_list and an empty list (i.e. [ ] ). sum() combines my_list and [ ] to produce a flattened list.

How do I merge nested lists in Python?

First, flatten the nested lists. Take Intersection using filter() and save it to 'lst3'. Now find elements either not in lst1 or in lst2, and save them to 'temp'. Finally, append 'temp' to 'lst3'.


1 Answers

Here's a recursive approach that is string friendly:

nests = [1, 2, [3, 4, [5],['hi']], [6, [[[7, 'hello']]]]]  def flatten(container):     for i in container:         if isinstance(i, (list,tuple)):             for j in flatten(i):                 yield j         else:             yield i  print list(flatten(nests)) 

returns:

[1, 2, 3, 4, 5, 'hi', 6, 7, 'hello'] 

Note, this doesn't make any guarantees for speed or overhead use, but illustrates a recursive solution that hopefully will be helpful.

like image 129
hexparrot Avatar answered Sep 19 '22 13:09

hexparrot