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])]]], []]
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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'
Method 2
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
Method 3
This can also be achieved with itertools.chain.from_iterable which will flatten the consecutive iterables:
import itertools
for item in itertools.chain.from_iterable(iterables):
# do something with item
Method 4
if you don’t want recursion you could try:
x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
layer1=x
layer2=[]
while True:
for i in layer1:
if isinstance(i,list):
for j in i:
layer2.append(j)
else:
print i
layer1[:]=layer2
layer2=[]
if len(layer1)==0:
break
which gives:
sam Test Test2 (u'file.txt', ['id', 1, 0]) (u'file2.txt', ['id', 1, 2]) one
(note that it didn’t look into the tuples for lists because the tuples aren’t lists. You can add tuple to the “isinstance” method if you want to fix this)
Method 5
It sounds like you need to use recursion. Make a function to iterate through a list, and if it hits an item that is also a list, call itself to iterate on the member. Here’s a link to something similar:
http://www.saltycrane.com/blog/2008/08/python-recursion-example-navigate-tree-data/
Method 6
If you wonder to get all values in the same list you can use the following code:
text = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
def get_values(lVals):
res = []
for val in lVals:
if type(val) not in [list, set, tuple]:
res.append(val)
else:
res.extend(get_values(val))
return res
get_values(text)
Method 7
Create a method to recursively iterate through nested lists. If the current element is an instance of list, then call the same method again. If not, print the current element. Here’s an example:
data = [1,2,3,[4,[5,6,7,[8,9]]]]
def print_list(the_list):
for each_item in the_list:
if isinstance(each_item, list):
print_list(each_item)
else:
print(each_item)
print_list(data)
Method 8
x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
output = []
def lister(l):
for item in l:
if type(item) in [list, tuple, set]:
lister(item)
else:
output.append(item)
lister(x)
Method 9
two nested for loops?
for a in x:
print "--------------"
for b in a:
print b
It would help if you gave an example of what you want to do with the lists
Method 10
# house list of lists
house = [["hallway", 11.25], ["kitchen", 18.0], ["living room", 20.0],
["bedroom", 10.75], ["bathroom", 9.50]]
for key, y in house :
print('The ' + key + ' is ' + str(y) + ' sqm ')
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0