Reputation: 43
I have a list b which contains the values
(0,3,[(1,0),(0,-1)])
How would I go about iterating through this list so i can get the values from both the outer list and the tuples? My current idea would be to make a variable equal to b[0] and b[1] as this will not expand and it will only hold 2 values. The list of tuples however, can expand so how would i go through the list to get the tuples?.
Thanks for the help.
Upvotes: -1
Views: 65
Reputation: 620
If you are using Python 3.3+ you can do the following:
def flatten(l):
for i in l:
if hasattr(i, '__iter__'):
yield from flatten(i)
else:
yield i
Than call the method like:
nested_list = (0,3,[(1,0),(0,-1)])
for i in flatten(nested_list):
print(i)
In Python version lower than 3.3 you cannot use 'yield from', and instead have to do this:
def flatten(l):
for i in l:
if hasattr(i, '__iter__'):
for i2 in flatten(i):
yield i2
else:
yield i
Upvotes: 0
Reputation: 44152
I know, you asked for iterating, but in case, the structure (nested tuple, list and tuple) are of fixed lengths, then you might use unpacking, which allows assigning values to some variable in one step.
>>> data = (0,3,[(1,0),(0,-1)])
>>> a, b, ((x1, y1), (x2, y2)) = data
>>> a
0
>>> b
3
>>> x1
1
>>> y1
0
>>> x2
0
>>> y2
-1
Upvotes: 0
Reputation: 32197
You can do it by defining a custom method:
b = (0, 3, [(1,0),(0,-1)])
def print_list(l):
for i in l:
if isinstance(i, list) or isinstance(i, tuple):
print_list(i)
else:
print i
>>> print_list(b)
0
3
1
0
0
-1
Upvotes: 2