Besides minor corrections in your code (questions raised by @Zero Piraeus), your question probably answered here . Possible code to iterate over a list of lists in N-degree (tree):
def traverse(item): try: for i in iter(item): for j in traverse(i): yield j except TypeError: yield item
Example:
l = [1, [2, 3], [4, 5, [[6, 7], 8], 9], 10] print [i for i in traverse(l)] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The key to getting it to work is recursion, and the key to make it work is to use a generator (the yield keyword gives a hint). The generator will iterate over your list of lists, returning you item by item, without having to copy data or create a completely new list (unless you use the entire generator that assigns the result to the list, as in my example)
Using iterators and generators can be a strange concept to understand (the yield keyword is mostly). Complete this great answer to fully understand them.
source share