
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Combining tuples in list of tuples in Python
For data analysis, we sometimes take a combination of data structures available in python. A list can contain tuples as its elements. In this article we will see how we can combine each element of a tuple with another given element and produce a list tuple combination.
With for loop
In the below approach we create for loops that will create a pair of elements by taking each element of the tuple and looping through the element in the list.
Example
Alist = [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')] # Given list of tuple print("List of tuples : \n",Alist) # Combine tuples in list of tuples res = [(t1, t2) for i, t2 in Alist for t1 in i] # print result print("The list tuple combination : \n" ,res)
Output
Running the above code gives us the following result −
List of tuples : [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')] The list tuple combination : [(2, 'Mon'), (8, 'Mon'), (9, 'Mon'), (7, 'Wed'), (5, 'Wed'), (6, 'Wed')]
With product
The itertools module has iterator named product which creates Cartesian product of parameters passed onto it. In this example we design for loops to go through each element of the tuple and form a pair with the non-list element in the tuple.
Example
from itertools import product Alist = [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')] # Given list of tuple print("List of tuples : \n",Alist) # Combine tuples in list of tuples res = [x for i, j in Alist for x in product(i, [j])] # print result print("The list tuple combination : \n" ,res)
Output
Running the above code gives us the following result −
List of tuples : [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')] The list tuple combination : [(2, 'Mon'), (8, 'Mon'), (9, 'Mon'), (7, 'Wed'), (5, 'Wed'), (6, 'Wed')]
- Related Questions & Answers
- Count tuples occurrence in list of tuples in Python
- Remove duplicate tuples from list of tuples in Python
- Summation of tuples in list in Python
- Convert list of tuples into list in Python
- Remove tuples from list of tuples if greater than n in Python
- Python program to find Tuples with positive elements in List of tuples
- Convert list of tuples to list of list in Python
- Remove tuples having duplicate first value from given list of tuples in Python
- Python program to find Tuples with positive elements in a List of tuples
- Finding frequency in list of tuples in Python
- Custom sorting in list of tuples in Python
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- Convert dictionary to list of tuples in Python
- Convert list of tuples into digits in Python