# [Tutor] Recursively flatten the list

Rafael Durán Castañeda rafadurancastaneda at gmail.com
Thu Mar 24 10:44:12 CET 2011

```I can do it with two list comprehensions:

>>> list_ = [1, 2, [3, 4], 5, [6, 7, 8], 9]
>>> [x[i] for x in list_ if isinstance(x, list) for i in range(len(x))] + [x
for x in list_ if not isinstance(x, list)]
[3, 4, 6, 7, 8, 1, 2, 5, 9]
>>>

But i loose original order, Can anyone do it with just one list
comprehension and/or keeping the order?

I also tryied:

>>> [x if not isinstance(x, list) else (x[i] for i in range(len(x))) for x
in list_]
[1, 2, <generator object <genexpr> at 0x187f7d0>, 5, <generator object
<genexpr> at 0x187f870>, 9]
>>> [x if not isinstance(x, list) else [x[i] for i in range(len(x))] for x
in list_]
[1, 2, [3, 4], 5, [6, 7, 8], 9]
>>>

2011/3/24 Tom Zych <freethinker at pobox.com>

> Dharmit Shah wrote:
> > I am learning Python and yesterday I cam across a definition wherein I
> was
> > supposed to flatten a list recursively. I am getting the solution
> properly
> > but wanted to know if I can optimize the code further.
> >
> > #!/usr/bin/env python
> > new_list=[]
> > def flatten(num_list):
> >     """
> >       >>> flatten([2, 9, [2, 1, 13, 2], 8, [2, 6]])
> >       [2, 9, 2, 1, 13, 2, 8, 2, 6]
> >       >>> flatten([[9, [7, 1, 13, 2], 8], [7, 6]])
> >       [9, 7, 1, 13, 2, 8, 7, 6]
> >       >>> flatten([[9, [7, 1, 13, 2], 8], [2, 6]])
> >       [9, 7, 1, 13, 2, 8, 2, 6]
> >       >>> flatten([[5, [5, [1, 5], 5], 5], [5, 6]])
> >       [5, 5, 1, 5, 5, 5, 5, 6]
> >     """
> >     global new_list
> >     for i in num_list:
> >         if type(i) == type([]):
> >             new_list = flatten(i)
> >         else:
> >             new_list.append(i)
> >     tmp = new_list
> >     new_list=[]
> >     return tmp
> >
> > if __name__=="__main__":
> >     import doctest
> >     doctest.testmod()
> >
> > PS - My knowledge of Python is still very basic and I am trying to dive
> into
> > it as deeper as I can. Solutions on Stackoverflow.com were beyond my
> > understandability.
>
> Using doctest and getting a recursive function right don't strike me as
> basic.  This is pretty good for a beginner.
>
> I'll second Peter Otten regarding the use of a global.  It's best to
> avoid using globals whenever possible, not just for reentrancy, but for
> more readable and maintainable code.  A function should be self-contained
> if possible.  There's no reason you can't use a local variable in this
> code (and you only need one, not two), and the resulting code would be
>
> Regarding this line:
>    if type(i) == type([]):
>
> This also works:
>    if type(i) == list:
>
> But this is better:
>    if isinstance(i, list):
>
> isinstance(obj, class) means "is obj an instance of class or a subtype
> of class", so it's more general.
>
> Does anyone see a way to do this with a list comprehension?  I don't.
> Would be a neat hack if it can be done.
>
> --
> Tom Zych / freethinker at pobox.com
> "Because if they didn't vote for a lizard," said Ford, "the wrong lizard
> might get in." -- DNA
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110324/c4aa4caa/attachment-0001.html>
```