Flatten list of tuples python

Python allows you to create lists of tuples where each item of list is a tuple. Sometimes you may need to flatten a list of tuples in python to obtain a single list of items, and use it further in your application. In this article, we will look at how to flatten list of tuples.

There are many ways to flatten list of tuples in Python. Let us say you have the following list of tuples.

>>> a=[(1,2),(3,4),(5,6)]

1. Using sum

This is the easiest and fastest method to convert a list of tuples. We use sum function to add an empty tuple to our list of tuples. The result is a single tuple of all elements. We convert this tuple into list using list function. Please note, list function is available only in python 3+.

>>> sum(a,())
(1, 2, 3, 4, 5, 6)
>>> list(sum(a,()))
[1, 2, 3, 4, 5, 6]
# one line command
>>> b=list(sum(a,()))
>>> b
[1, 2, 3, 4, 5, 6]

2. Using itertools

itertools is a useful library that allows you to easily work with iterable data structure like lists. It provides chain function that allows you to easily flatten a list. Here is an example.

>>> import itertools
>>> list(itertools.chain(*a))
[1, 2, 3, 4, 5, 6]
>>> list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]

3. Using List Comprehension

You an also use list comprehensions to flatten a list of tuples as shown below. In this case, we basically loop through our list of tuples to construct our flattened list.

>>> b = [item for sublist in a for item in sublist]
[1, 2, 3, 4, 5, 6]

4. Using extend

You may also use extend method to flatten list of tuple. But please note, this method is slower than others and supported only in Python 3+.

>>> b = [] 
>>> list(b.extend(item) for item in a)
>>> b
[1, 2, 3, 4, 5, 6]

In this article, we have looked at various methods to flatten list of tuples. Out of them, the first method is the fastest, simplest and most recommended. However, it uses list() function which is available in python 3+. If you use python <3, then use itertools instead (method 2).

Also read:

How to Find & Delete Broken Symlinks in Linux
How to Remove Duplicates from List in Python
How to Get Key from Value in Python Dictionary
How to Flatten List of Lists in Python
How to Find Element in List in Python

Update: Flattening using extend but without comprehension and without using list as iterator (fastest)

After checking the next answer to this that provided a faster solution via a list comprehension with dual for I did a little tweak and now it performs better, first the execution of list(...) was dragging a big percentage of time, then changing a list comprehension for a simple loop shaved a bit more as well.

The new solution is:

l = []
for row in output: l.extend(row)

The old one replacing list with [] (a bit slower but not much):

[l.extend(row) for row in output]

Older (slower):

Flattening with list comprehension

l = []
list(l.extend(row) for row in output)

some timeits for new extend and the improvement gotten by just removing list(...) for [...]:

import timeit
t = timeit.timeit
o = "output=list(zip(range(1000000000), range(10000000))); l=[]"
steps_ext = "for row in output: l.extend(row)"
steps_ext_old = "list(l.extend(row) for row in output)"
steps_ext_remove_list = "[l.extend(row) for row in output]"
steps_com = "[item for sublist in output for item in sublist]"

print(f"{steps_ext}\n>>>{t(steps_ext, setup=o, number=10)}")
print(f"{steps_ext_remove_list}\n>>>{t(steps_ext_remove_list, setup=o, number=10)}")
print(f"{steps_com}\n>>>{t(steps_com, setup=o, number=10)}")
print(f"{steps_ext_old}\n>>>{t(steps_ext_old, setup=o, number=10)}")

Time it results:

for row in output: l.extend(row)                  
>>> 7.022608777000187

[l.extend(row) for row in output]
>>> 9.155910597999991

[item for sublist in output for item in sublist]
>>> 9.920002304000036

list(l.extend(row) for row in output)
>>> 10.703829122000116

Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have lists as its constituent elements. This kind of problem is common in data domains such as Machine Learning. Let’s discuss certain ways in which this task can be performed.

Input : test_tuple = ([5], [6], [3], [8]) Output : (5, 6, 3, 8) Input : test_tuple = ([5, 7, 8]) Output : (5, 7, 8)

Method #1 : Using sum() + tuple() The combination of above functions can be used to solve this problem. In this, we perform the task of flattening using sum(), passing empty list as its argument. 

Python3

test_tuple = ([5, 6], [6, 7, 8, 9], [3])

print("The original tuple : " + str(test_tuple))

res = tuple(sum(test_tuple, []))

print("The flattened tuple : " + str(res))

Output : 

The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)

  Method #2 : Using tuple() + chain.from_iterable() The combination of above functions can be used to solve this problem. In this, we perform task of flattening using from_iterable() and conversion to tuple using tuple(). 

Python3

from itertools import chain

test_tuple = ([5, 6], [6, 7, 8, 9], [3])

print("The original tuple : " + str(test_tuple))

res = tuple(chain.from_iterable(test_tuple))

print("The flattened tuple : " + str(res))

Output : 

The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)

Method #3: Using extend() and tuple() methods

Python3

test_tuple = ([5, 6], [6, 7, 8, 9], [3])

print("The original tuple : " + str(test_tuple))

res=[]

for i in test_tuple:

    res.extend(i)

res=tuple(res)

print("The flattened tuple : " + str(res))

Output :

The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)
 


How do you flatten a list of tuples in Python?

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.

How do I make a list out of a list of tuples?

If you're in a hurry, here's the short answer: Use the list comprehension statement [list(x) for x in tuples] to convert each tuple in tuples to a list. This also works for a list of tuples with a varying number of elements.

How do you flatten a multi list in Python?

There are three ways to flatten a Python list:.
Using a list comprehension..
Using a nested for loop..
Using the itertools. chain() method..

How do you convert a tuple to a list in Python?

We can use the list() function to convert tuple to list in Python. After writing the above code, Ones you will print ” my_tuple ” then the output will appear as a “ [10, 20, 30, 40, 50] ”. Here, the list() function will convert the tuple to the list.