Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through list of list in Python

Tags:

python

list

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])]]], []] 
like image 907
sam Avatar asked Jun 14 '11 07:06

sam


People also ask

Can we use list in for loop in Python?

In Python, we can loop over list elements with for and while statements, and list comprehensions.


2 Answers

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' 
like image 168
Jeremy Avatar answered Sep 21 '22 18:09

Jeremy


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

like image 27
victorhooi Avatar answered Sep 17 '22 18:09

victorhooi