I have a list of tuples that looks like this:
[('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
I want to turn it into this:
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]
What is the most Pythonic way to do this?
I have a list of tuples that looks like this:
[('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
I want to turn it into this:
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]
What is the most Pythonic way to do this?
Adjust the canonical un-flatten recipe to only unflatten when there are tuples in the value:
This will only unwrap tuples, and only if there are other tuples in it:
one-line, using list comprehension:
yields:
this is artificially creating a list if the element is not a tuple of tuples, then flattening all does the job. To avoid creating a single element list
[x]
,(x for _ in range(1))
can also do the job (although it appears clunky)Limitation: doesn't handle more than 1 level of nesting. In which case, a more complex/recursive solution must be coded.
A one-line solution would be using
itertools.chain
: