L = [[[1, 2, 3], [4, 5]], 6]
The required output is
[1, 2, 3, 4, 5, 6]
Even better iterators. This question Is the only solution I see that works with any nesting:
def flatten(x): result =  for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result flatten(L)
Is this the best model?Is there anything wrong with me?
Use Recursive and Duck Type Generator (for Python 3 updates):
def flatten(L): for item in L: try: yield from flatten(item) except TypeError: yield item list(flatten([[[1, 2, 3], [4, 5]], 6])) >>>[1, 2, 3, 4, 5, 6]
It's interesting to try to create a function that flattens irregular lists in Python, but of course that's what Python does (making programming fun).The following generators work well on some warnings:
def flatten(iterable): try: for item in iterable: yield from flatten(item) except TypeError: yield iterable
It flattens data types you may want to keep independently (such as bytearray, bytes, and str objects).In addition, the code relies on the fact that requesting an iterator from an object that cannot be iterated causes a TypeError.
>>> L = [[[1, 2, 3], [4, 5]], 6] >>> def flatten(iterable): try: for item in iterable: yield from flatten(item) except TypeError: yield iterable >>> list(flatten(L)) [1, 2, 3, 4, 5, 6] >>>
I disagree with the previous implementation.The problem is that you shouldn't flatten things that can't be iterated.This is confusing and gives the wrong impression.
>>> list(flatten(123))  >>>
The following generators are almost identical to the first, but there are no problems trying to flatten non-iterative objects.When given an inappropriate parameter, it fails as expected.
def flatten(iterable): for item in iterable: try: yield from flatten(item) except TypeError: yield item
Testing the generator using the provided list works fine.However, the new code raises a TypeError when it is given a non-iterative object.An example of the new behavior is shown below.
>>> L = [[[1, 2, 3], [4, 5]], 6] >>> list(flatten(L)) [1, 2, 3, 4, 5, 6] >>> list(flatten(123)) Traceback (most recent call last): File "<pyshell#32>", line 1, in <module> list(flatten(123)) File "<pyshell#27>", line 2, in flatten for item in iterable: TypeError: 'int' object is not iterable >>>
Here, compiler.ast.flatten is implemented in 2.7.5:
def flatten(seq): l =  for elt in seq: t = type(elt) if t is tuple or t is list: for elt2 in flatten(elt): l.append(elt2) else: l.append(elt) return l
There are better, quicker ways (if you've been here, you've already seen them)
Also note that:
Deprecated since version 2.6: Compiler packages have been removed in Python 3.
This is a simple function to tile lists of any depth.No recursion to avoid stack overflow.
from copy import deepcopy def flatten_list(nested_list): """Flatten an arbitrarily nested list, without recursion (to avoid stack overflows). Returns a new list, the original list is unchanged. >> list(flatten_list([1, 2, 3, , , [[[[[[[[]]]]]]]]])) [1, 2, 3, 4, 5] >> list(flatten_list([[1, 2], 3])) [1, 2, 3] """ nested_list = deepcopy(nested_list) while nested_list: sublist = nested_list.pop(0) if isinstance(sublist, list): nested_list = sublist + nested_list else: yield sublist
import collections def flatten(x): if isinstance(x, collections.Iterable): return [a for i in x for a in flatten(i)] else: return [x]
More concise, but almost identical.