I want to iterate through list of list.
I want to iterate through irregularly nested lists inside list also.
Can anyone let me know how can I do that?
x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
In Python, we can loop over list elements with for and while statements, and list comprehensions.
This traverse
generator function can be used to iterate over all the values:
def traverse(o, tree_types=(list, tuple)): if isinstance(o, tree_types): for value in o: for subvalue in traverse(value, tree_types): yield subvalue else: yield o data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))] print list(traverse(data)) # prints [1, 1, 1, 1, 1, '1', 1, 1, 1, 1, 1, 1, 1, '1'] for value in traverse(data): print repr(value) # prints # 1 # 1 # 1 # 1 # 1 # '1' # 1 # 1 # 1 # 1 # 1 # 1 # 1 # '1'
So wait, this is just a list-within-a-list?
The easiest way is probably just to use nested for loops:
>>> a = [[1, 3, 4], [2, 4, 4], [3, 4, 5]] >>> a [[1, 3, 4], [2, 4, 4], [3, 4, 5]] >>> for list in a: ... for number in list: ... print number ... 1 3 4 2 4 4 3 4 5
Or is it something more complicated than that? Arbitrary nesting or something? Let us know if there's something else as well.
Also, for performance reasons, you might want to look at using list comprehensions to do this:
http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With