walking a list

M

mr.happy

Hi all,

I have this little question, basicly i solved it already by writing a
little bit of code for it (using recursion), but still i am wondering if
there is a shorter ways to do things (like 1 or 2 commands).

the problem is this, imagine i have a list:

list = [1, 2, [3, 2], 5, [6, 5, 4]]

if i print out this list using 'for element in list: print element,'
it will show me the following:

1
2
[3, 2]
5
[6, 5, 4]

but what i really want to show is:

1
2
3
2
5
6
5
4

What i want to do is run through the list and when i get back a list run
through that list as well (and if that list contains a list run through it
again etc.).

all suggestions are welcome, i'm ready to learn from the pro's ;)
 
J

Jeff Epler

def print_or_recurse(l):
for i in l:
if isinstance(i, list): print_or_recurse(i)
else: print i

print_or_recurse([1,2,[3,2],5,[6,5,4]])

Jeff
 
M

mr.happy

if isinstance(i, list): print_or_recurse(i)

great! thanks, i didn't know 'isinstance' existed.
what i did was the following:

if 'list' in str(type(list)):

it worked as well :)
 

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
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top