# List Recursion

Justin Dubs jtdubs at eos.ncsu.edu
Fri Nov 16 16:52:24 CET 2001

```"Daniel Klein" <danielk at aracnet.com> wrote in message
news:pr5avt0i0qkhpqml83ijtk66pioc78st9p at 4ax.com...
> Now that I've gone thru the exercise to write a whole 6 lines of python
code to 'visit' nested list
> elements, I'm wondering if there is a builtin utility for this, or if
someone has come up with a
> better/faster method. Of course, this will eventually be a class method
that 'returns' each object
> in the list...
>
> >>> list1 = ['a', 'b']
> >>> list2 = ['1', ['a', 'b'], '2']
> >>> import types
> >>> def visitEachListElementOf(alist):
>  for el  in alist:
>   if isinstance(el, types.ListType):
>    visitEachListElementOf(el)
>   else:
>    print el      # do whatever is necessary with the list element
>
> >>> visitEachElelementOf(list2)
> 1
> a
> b
> 2
> >>>
>
> Daniel Klein
>
> "Give a man a computer program and you give him a headache.  But teach him
to program computers and
> you give him the power to create headaches for others the rest of his
life!" -- Unknown
>
>
>

You may want to check out generators.  They are in __future__ right now, but
they will make doing things like that a lot prettier.  Check out this code:

>>> from __future__ import generators
>>> import types
>>> def leaves(L):
...    for node in L:
...        if isinstance(node, types.ListType):
...            for leaf in leaves(node):
...                yield leaf
...        else:
...            yield node
...
>>> list1 = [1, [2, 3], [4, 5, [6, [7]]], 8, 9]
>>> for leaf in leaves(list1): print leaf,
...
1 2 3 4 5 6 7 8 9
>>> for leaf in leaves(list1): print (leaf * 2 + 1)
...
3 5 7 9 11 13 15 17 19
>>> [leaf for leaf in leaves(list1)]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Anyway, hope that gives you some ideas.  As for your actual algorithm
though, I couldn't think of a better way offhand.  Have fun,

Justin Dubs

```