Possible Duplicate:
Flatten (an irregular) list of lists in Python
Example 1:
Lets say I have a list: [[1,2], [3,4]]. I could use two for loops to be able to print out: 1, 2, 3, 4.
Example 2:
So, now let’s suppose that I’m given an output and I don’t know how many nested lists there within list1:
list1 = [1, [1, 2, [3, 5, 6,[ .. ], …, ] ] ] ] ]
So, my question is how would I be able to print out every individual number in the same format as the first example. I’m working with something right now that gives me nested lists as a result, but different inputs to the function will give me different amount of nested lists.
What I can think of is to do this, but I don’t know what to do after the isinstance part:
c = 0
for i in list1:
while c < len(list1):
if isinstance(i, list):
else:
print i
c += 1
Thanks
First Edit
If there is also a way to deconstruct all the nested lists to become a single list that would work as well for me, but I’m curious to know answers to both these problems.
The itertools documentation has some pretty good examples of iterating over lists and such, so it’s always a good place to start when faced with such a task.
I would recomend using a generator, which avoid creating many levels of lists:
Application:
Edit: Non-recursive linear version