walking a list

Discussion in 'Python' started by mr.happy, Apr 23, 2004.

  1. mr.happy

    mr.happy Guest

    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 ;)

    --
    One monk said to the other, "The fish has flopped out of the net! How will it
    live?" The other said, "When you have gotten out of the net, I'll tell you."
    mr.happy, Apr 23, 2004
    #1
    1. Advertising

  2. mr.happy

    Jeff Epler Guest

    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
    Jeff Epler, Apr 23, 2004
    #2
    1. Advertising

  3. mr.happy

    mr.happy Guest

    On Fri, 23 Apr 2004 13:21:43 -0500, Jeff Epler wrote:

    > 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 :)

    --
    One monk said to the other, "The fish has flopped out of the net! How will it
    live?" The other said, "When you have gotten out of the net, I'll tell you."
    mr.happy, Apr 24, 2004
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mikito Harakiri

    tree walking -- saved recursion state

    Mikito Harakiri, Jan 3, 2004, in forum: Java
    Replies:
    13
    Views:
    702
    Matt Humphrey
    Jan 5, 2004
  2. Tina - AffordableHOST.com

    Re: Pain while walking

    Tina - AffordableHOST.com, Jul 14, 2003, in forum: HTML
    Replies:
    0
    Views:
    382
    Tina - AffordableHOST.com
    Jul 14, 2003
  3. Tim Burch

    Re: Pain while walking

    Tim Burch, Jul 14, 2003, in forum: HTML
    Replies:
    5
    Views:
    421
    T. Audry Glamour
    Jul 16, 2003
  4. Whitecrest

    Re: Pain while walking

    Whitecrest, Jul 14, 2003, in forum: HTML
    Replies:
    5
    Views:
    1,933
    Whitecrest
    Jul 15, 2003
  5. Replies:
    5
    Views:
    340
    Richard Herring
    Feb 8, 2006
Loading...

Share This Page