2

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
1

2 Answers 2

4

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
$
@
Sign up to request clarification or add additional context in comments.

Comments

0

A slight modification of Mohammad Yusuf's answer with a few QOL changes:

  1. Depth tracking/limit, either because you're only interested in layers up to a certain depth or to avoid blowing up on very deep nested tuples.
  2. Configurable depth-based print indenting to help illustrate structure.
def foo(a, depth=0, depth_lim=10, indent_size=1, indent_str="-"):
    # Set up indent and increment depth counter
    indent = indent_str * ((depth) * indent_size)
    depth += 1
    
    #Loop over elements and print if we're not at the depth limit
    if depth <= depth_lim:
        for b in a:
            if isinstance(b, tuple):
                foo(b, depth, depth_lim, indent_size, indent_str)
            else:
                print(indent + str(b))
    else:
        print("Depth limit reached (" + str(depth_lim) + 
              "). Increase depth_lim for deeper printing.")

Example use:

test_tuple = ("a",(("c"),("d"),(("e"),("f"))), "b")
foo(test_tuple, indent_size=2)

Output:

a
--c
--d
----e
----f
b

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.