A more general solution

Tim Chase python.list at tim.thechases.com
Sun May 9 07:42:02 EDT 2010


On 05/08/2010 10:33 PM, 3Jane wrote:
> You could interpret [[1,2,3,4],[5,6,7,8]] as a tree and
> your task as traversal of its leaves. All solutions before
> would not work with trees with bigger height.
>
> Here is how to traverse such trees recursively:
>
> def eventualPrint(x):
>      for v in x:
>          if isinstance(v, list): eventualPrint(x)
>          else: print(v)
>
> Then eventualPrint(a) does the job.

Caveat:  ...but wanders off into the bushes for recursive lists :)

   x = [1,2,3]
   x.append (x)
   eventualPrint(x)

Not a particular concern in this case since I'm now two levels of 
hypothetical removed from the OP's question (from flatten one 
layer to recursively flattening arbitrary nestings to recursively 
flattening arbitrary & self-referential nestings)...

For the record, I'm in the itertools camp of proposed solutions 
to the OP's question.

-tkc





More information about the Python-list mailing list