
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert List of Tuples into List in Python
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
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
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
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']