PeterPefi
PeterPefi

Reputation: 99

Flattening of nested tuples

Can you flatten a tuple such as this:

(42, (23, (22, (17, []))))

To become one tuple of all elements:

(42,23,22,17)

?

Upvotes: 1

Views: 186

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195458

A solution using recursion:

tpl = (42, (23, (22, (17, []))))

def flatten(tpl):
    if isinstance(tpl, (tuple, list)):
        for v in tpl:
            yield from flatten(v)
    else:
        yield tpl

print(tuple(flatten(tpl)))

Prints:

(42, 23, 22, 17)

Upvotes: 5

Related Questions