List Recursion

Daniel Klein danielk at aracnet.com
Fri Nov 16 08:54:53 EST 2001


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






More information about the Python-list mailing list