1

Can you flatten a tuple such as this:

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

To become one tuple of all elements:

(42,23,22,17)

?

PeterPefi
  • 87
  • 1
  • 1
  • 7
  • Does this answer your question? [Flatten an irregular list of lists](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists) – oreopot Jun 14 '20 at 22:05

1 Answers1

5

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)
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    Wow, thanks so much! Could you explain how this works? I don’t get this line: „if isinstance(tpl, (tuple, list)):“. Is the „tuple“ here just the first value, so 42 in the first run? – PeterPefi Jun 15 '20 at 10:04
  • 1
    @PeterPefi No, in `(42, (23, (22, (17, []))))` you have many tuples: `(42, (23, (22, (17, []))))`, `(23, (22, (17, [])))`, `(22, (17, []))`, `(17, [])` and one list: `[]`. `isinstance(tpl, (tuple, list))` just tests if variable `tpl` is of type `tuple` or `list` – Andrej Kesely Jun 15 '20 at 10:35
  • Ah okay, so you can add as many types into an isinstance query as you want. – PeterPefi Jun 15 '20 at 10:44