A more general solution

3Jane 1 at depikt.net
Sat May 8 23:33:14 EDT 2010


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. This would
only cope with lists as proper nodes. More
general tests than isinstance() could be tried,

    hasattr(x, 'getitem')

would match all sequence types for example.
Also "for v in x:" should perhaps tested for
exceptions. Optimal directives for both
alternatives depend on the scope of the code's
purpose.

As often the price for generality is performance
here.

Good luck, Joost



More information about the Python-list mailing list