Reputation: 99
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
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