Convert list of tuples into list in Python

PythonServer Side ProgrammingProgramming

We may come across a lists whose elements are tuples. But for further data processing we may need to convert the tuples to the normal elements of a list. In this article we will see the approaches to achieve this.

With list comprehension

In this approach we design nested for loops to iterate through each tuple and produce the final list of elements.

Example

 Live Demo

listA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]
# Given list
print("Given list : \n", listA)
res = [item for t in listA for item in t]
# Result
print("Final list: \n",res)

Output

Running the above code gives us the following result −

Given list :
[('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]
Final list:
['Mon', 3, 'Wed', 4, 'Fri', 7, 'pm']

With itertools

We can also use the itertools.chain method along with * operator which will fetch each element in the list of tuples and then combine them as a series of elements for the list.

Example

 Live Demo

import itertools
listA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]
# Given list
print("Given list : \n", listA)
res = list(itertools.chain(*listA))
# Result
print("Final list: \n",res)

Output

Running the above code gives us the following result −

Given list :
[('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]
Final list:
['Mon', 3, 'Wed', 4, 'Fri', 7, 'pm']

With reduce and concat

The reduce function in used to apply the concat function to each of the list elements which finally produces a list of all elements from the original list.

Example

 Live Demo

import operator
from functools import reduce
listA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]
# Given list
print("Given list : \n", listA)
res = (list(reduce(operator.concat, listA)))
# Result
print("Final list: \n",res)

Output

Running the above code gives us the following result −

Given list :
[('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')]
Final list:
['Mon', 3, 'Wed', 4, 'Fri', 7, 'pm']
raja
Published on 20-May-2020 14:32:48
Advertisements