How to flatten a tuple in python How to flatten a tuple in python python python

How to flatten a tuple in python


[(a, b, c) for a, (b, c) in l]

Tuple packing and unpacking solves the problem.


New in Python 3.5 with the additional tuple unpacking introduced in PEP 448, you can use starred expressions in tuple literals such that you can use

>>> l = [(50, (2.7387451803816479e-13, 219)), (40, (3.4587451803816479e-13, 220))]>>> [(a, *rest) for a, rest in l][(50, 2.738745180381648e-13, 219), (40, 3.458745180381648e-13, 220)]

This could be useful if you had a nested tuple used for record-keeping with many elements that you wanted to flatten.


Your could use the following function and apply it in a loop to every element in the list.

def flatten(data):    if isinstance(data, tuple):        if len(data) == 0:            return ()        else:            return flatten(data[0]) + flatten(data[1:])    else:        return (data,)

How it works:

  • First it will be checked if type is tuple, if not, it "tuples" the argument
  • Second line returns an empty tuple, if tuple is empty
  • Third line gets out the first element and calls the function recursively

The nice thing in this solution is:

  • It is not necessary to know the structure of the given tuple
  • The tuple can be nested arbitrarily deep
  • Works in Python 2.2+ (and probably earlier)

The code is slightly adapted from following source:
https://mail.python.org/pipermail/tutor/2001-April/005025.html

Hope it helps someone :)