A more general solution

3

3Jane

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
 
T

Tim Chase

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top