covariance covariance - 28 days ago 10
Python Question

How to flatten a list with various data types (int, tuple)

Say I have a list with one or more tuples in it:

[0, 2, (1, 2), 5, 2, (3, 5)]


What's the best way to get rid of the tuples so that it's just an int list?

[0, 2, 1, 2, 5, 2, 3, 5]

Answer

One of solutions (using itertools.chain):

>>> from itertools import chain
>>> l = [0, 2, (1, 2), 5, 2, (3, 5)]
>>> list(chain(*(i if isinstance(i, tuple) else (i,) for i in l)))
[0, 2, 1, 2, 5, 2, 3, 5]
Comments