Flattening lists

jason-sage at creativetrax.com jason-sage at creativetrax.com
Thu Feb 5 10:22:29 EST 2009


mk wrote:
> Hello everybody,
>
> Any better solution than this?
>
> def flatten(x):
>     res = []
>     for el in x:
>         if isinstance(el,list):
>             res.extend(flatten(el))
>         else:
>             res.append(el)
>     return res
>
> a = [1, 2, 3, [4, 5, 6], [[7, 8], [9, 10]]]
> print flatten(a)

It depends on what you mean by "better".  More features?  Here is the 
function from Sage (http://www.sagemath.org), which is a modified 
version of a more standard implementation to give a max_level argument.

The first few lines of documentation:

def flatten(in_list, ltypes=(list, tuple), max_level=sys.maxint):
   """
   Flattens a nested list.

   INPUT:
       in_list -- a list or tuple
       ltypes -- optional list of particular types to flatten
       max_level -- the maximum level to flatten

   OUTPUT:
       a flat list of the entries of in_list

(lots of examples follow this documentation)

The implementation:  
http://www.sagemath.org/hg/sage-main/file/b0aa7ef45b3c/sage/misc/flatten.py


Jason




More information about the Python-list mailing list