Combining tuples in list of tuples in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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')]
raja
Published on 20-May-2020 13:48:55
Advertisements