To flatten a list of tuples in Python, the easiest way is to use list comprehension.

list_of_tuples = [(0, 1), (2, 3), (4, 5)]

flattened_list = [x for tuple in list_of_tuples for x in tuple]

print(flattened_list)

#Output:
[0, 1, 2, 3, 4, 5]

You can also use the sum() function.

list_of_tuples = [(0, 1), (2, 3), (4, 5)]

flattened_list = list(sum(list_of_tuples,()))

print(flattened_list)

#Output:
[0, 1, 2, 3, 4, 5]

When working with collections of data, the ability to easily modify the structure and create new structures can be useful.

One such situation is if you have a list of tuples and want to flatten the list of tuples to create a simple list.

To flatten a list of tuples in Python, the easiest way is to use list comprehension.

Below is an example which will flatten a list of tuples using list comprehension in Python.

list_of_tuples = [(0, 1), (2, 3), (4, 5)]

flattened_list = [x for tuple in list_of_tuples for x in tuple]

print(flattened_list)

#Output:
[0, 1, 2, 3, 4, 5]

Using sum() to Flatten List of Tuples in Python

Another method you can use to flatten a list of tuples is with the Python sum() function.

The key here is that you need to pass a second value which will be the starting point for the sum() function.

In this case, we want to pass an empty tuple to sum() so that we can build a new list from scratch.

Below is an example showing you how to use sum()list_of_tuples = [(0, 1), (2, 3), (4, 5)] flattened_list = list(sum(list_of_tuples,())) print(flattened_list) #Output: [0, 1, 2, 3, 4, 5]

Hopefully this article has been useful for you to be able to flatten a list of tuples in Python.

Categorized in:

Python,

Last Update: March 11, 2024