Skip to content Skip to sidebar Skip to footer

How Do I Flatten Deeply Nested Tuples?

I'm given a nested structure of tuples with 2 elements each, and want to convert it to a flat structure I've tried using * to loop through and flatten, but am stuck since each tupl

Solution 1:

Using recursion

defconvert(data):
    result = []
    for item in data:
        ifisinstance(item, tuple):
            result.extend(convert(item))
        else:
            result.append(item)
    returntuple(result)

data = (((((1, 2), 3), 4), 5), 6)
print(convert(data))

Solution 2:

You can use recursion with a generator for a shorter, cleaner solution:

defflatten(d):
  for i in d:
     yieldfrom [i] ifnotisinstance(i, tuple) else flatten(i)

print(tuple(flatten((((((1, 2), 3), 4), 5), 6))))

Output:

(1, 2, 3, 4, 5, 6)

Solution 3:

Being witty:

def flatten(T):ifT==():returnTif isinstance(T[0], tuple):return flatten(T[0])+ flatten(T[1:])returnT[:1]+ flatten(T[1:])


s =(((((1,2),3),4),5),6)
print("Flattened tuple: ", flatten(s))

OUTPUT:

Flattened tuple:  (1, 2, 3, 4, 5, 6)

Post a Comment for "How Do I Flatten Deeply Nested Tuples?"