Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 587
covariance Avatar asked Mar 21 '14 20:03

covariance


People also ask

How do you flatten a list to a tuple?

One method to flatten tuples of a list is by using the sum() method with empty lust which will return all elements of the tuple as individual values in the list. Then we will convert it into a tuple. Method 2: Another method is using a method from Python's itertools library.


2 Answers

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]
like image 176
ndpu Avatar answered Oct 11 '22 13:10

ndpu


Using a nested list comprehension:

>>> lst = [0, 2, (1, 2), 5, 2, (3, 5)]
>>> [y for x in lst for y in (x if isinstance(x, tuple) else (x,))]
[0, 2, 1, 2, 5, 2, 3, 5]
like image 45
Andrew Clark Avatar answered Oct 11 '22 13:10

Andrew Clark