7

I have a data structure like this (the actual lists of lists are very long and of varying depth). I do know their depth beforehand.

 a=( [1,2], [2,3,[4,5]] )
 b=( [[1,2],[2,3]] )

A want to loop through each single list. How to best do this?

I don't want to end up doing something like this:

for l in a:
    if instance(l, list):
        for ll in l:
            if instance(ll, list): 
                ...
10
  • 1
    "I do know their depth beforehand." - is there a missing "not"? Commented Nov 11, 2013 at 13:53
  • 1
    hint: the more appropriate name of this data structure is tree, rather than list Commented Nov 11, 2013 at 13:54
  • 1
    What do you expect the loop to do for the input sample? Commented Nov 11, 2013 at 13:54
  • @Tim, No, I do know their depth. Commented Nov 11, 2013 at 13:54
  • @MartijnPieters, I want to pass the values to a matplotlib function Commented Nov 11, 2013 at 13:56

4 Answers 4

4

Since you don't defined the purpose, i'm coding a function that sum all elements:

def rec_sum(lst):
    if not lst:
        return 0
    el = lst.pop()
    if isinstance(el, list):
        return rec_sum(el) + rec_sum(lst)
    else:
        return el + rec_sum(lst)

Even if you know the depth beforehand, it's easier to solve using recursion.

Remember that Python limits 1000 stack frames stacked. So, if your list have more than 1000 items, you should get an Exception.

If you think you can have more than 1000 items, here it is a mixed solution, that uses recursion and for loops. It is limited into 1000 levels, instead of 1000 items:

def rec_for_sum(lst):
    if not lst:
        return 0
    count = 0
    for el in lst:
        if not isinstance(el, list):
            count += el
        else:
            count += rec_for_sum(el)
    return count
Sign up to request clarification or add additional context in comments.

Comments

1

You can check if an object is a list and just then go deeper:

Also see How to check if an object is a list or tuple (but not string)?

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

2 Comments

This doesn't answer the question (insofar that the question can be understood at all); it should have been a comment instead.
oh sry i clicked the wrong button first but now i edited it to a solution
1

You can use a combination of recursion and a generator:

def flatten_list(list_in):
    if isinstance(list_in,list):
        for l in list_in:
                for y in flatten_list(l):
                        yield y
    else:
        yield list_in


my_compound_list = [[1,2,3],[4,5,6],[7,8,9,[10,11,12,[13,14,15]]]]

print [f for f in flatten_list(my_compound_list)]

Comments

0

SIMPLE FORM OF ITERATIVE SOLUTION (BASIS NOT COMPLETE):

   for item in your_list:
        if isinstance(item,list):
           ...........
        else:
        ...................

This is a way you should go. This should be enough to get you started.

RECURSIVE SOLUTION:

def list_flatten(my_list):
    for item in my_list:
        if(isinstance(item,list)):
            list_flatten(item)
        else:
            print(item)

This is a recursive solution for your problem. But beware of memory problem and recursion depth.

1 Comment

Ok, but if the the data tree has a depth of let's say 10?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.