1

I'm new to python and trying to figure out how to iterate through a nested tuple.

here is a tuple:

x=((1,2,('a', 'b', (6,9,7)), 6,('$','@')))

I'm trying to iterate so I can print each value separately like:

1
2
a
b
6
9
7
6
$
@

Here is my code, please let me know what I'm doing wrong here:

x=((1,2,('a', 'b', (6,9,7)), 6,('$','@')))
f=0
for y in x:
   print(x[f])
   f = f+1
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78

1 Answers1

2

You can try with recursion. Check if element is tuple, if it is then make a recursive call to function, if it is not then print it.

x=(((1,2,3,4),2,('a', 'b', (6,9,7)), 6,('$','@')))

def foo(a):
    for b in a:
        if isinstance(b,tuple):
            foo(b)
        else:
            print b
foo(x)

Output:

1
2
3
4
2
a
b
6
9
7
6
$
@
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78