-3

As an output from a function, I get tuples in either the form a and b as shown below:

a = ((x, y), z)
b = (x, y)

I would like to flatten the nested form to be as follows:

a = (x, y, z)

This will always result in me having a tuple which is one layer deep, regardless of what I get as a return from my function.

What is the quickest and most efficient way to do this in Python 3?

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
hojkoff
  • 185
  • 1
  • 8

2 Answers2

1

You could try to unpack the tuple and catch any TypeError's:

def flatten(a):
    try:
        (x, y), z = a
        return x, y, z
    except TypeError:
        return a

print(flatten(((1, 2), 3)))  # (1, 2, 3)
print(flatten((1, 2)))  # (1, 2)
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
1

Use itertools.chain.from_iterable with tuple()

Ex:

from itertools import chain

a = (("x", "y"), "z")
b = ("x", "y")

for i in [a, b]:
    print(tuple(chain.from_iterable(i)))

Output:

('x', 'y', 'z')
('x', 'y')
Rakesh
  • 81,458
  • 17
  • 76
  • 113