From: 3Jane on
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
From: Tim Chase on
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