List of tuples to single tuple

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.


How to Flatten List of Tuples in Python

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

Chủ Đề