Open In App

Python | Combining tuples in list of tuples

Last Updated : 21 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let’s discuss certain ways in which this can be performed. 

Method #1: Using list comprehension We can solve this particular problem using the list comprehension technique in which we can iterate for each tuple list and join it with other tuple attributes to join. 

Step-by-step approach:

  • Create a list of tuples called test_list. Each tuple in the list contains a list of numbers and a string.
  • Print the original list using the print() function and concatenate the string “The original list : ” with the string representation of test_list using the str() function.
  • Create a list comprehension called res. This comprehension iterates over each tuple in test_list and unpacks the list of numbers and string. The for loop iterates over each number in the list of numbers and assigns the variable tup1 to that number. The variable tup2 is assigned to the string in the tuple. Finally, the comprehension appends a new tuple to the list res consisting of tup1 and tup2.
  • Print the result using the print() function and concatenate the string “The list tuple combination : ” with the string representation of res using the str() function.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# Combining tuples in list of tuples
# Using list comprehension
 
# initializing list
test_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using list comprehension
# Combining tuples in list of tuples
res = [(tup1, tup2) for i, tup2 in test_list for tup1 in i]
 
# print result
print("The list tuple combination : " + str(res))


Output

The original list : [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
The list tuple combination : [(1, 'gfg'), (2, 'gfg'), (3, 'gfg'), (5, 'cs'), (4, 'cs'), (3, 'cs')]

Time Complexity: O(n^2)
Auxiliary Space: O(n)

Method #2: Using product() + list comprehension Apart from using the tuple for generation of tuples, the product function can be used to get Cartesian product of list elements with tuple element, using the iterator internally. 

Python3




# Python3 code to demonstrate
# Combining tuples in list of tuples
# Using product() + list comprehension
from itertools import product
 
# initializing list
test_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using product() + list comprehension
# Combining tuples in list of tuples
res = [ele for i, j in test_list for ele in product(i, [j])]
 
# print result
print("The list tuple combination : " + str(res))


Output

The original list : [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
The list tuple combination : [(1, 'gfg'), (2, 'gfg'), (3, 'gfg'), (5, 'cs'), (4, 'cs'), (3, 'cs')]

Time complexity: O(n*m), where n is the number of tuples in the list and m is the maximum length of the tuples in the list.
Auxiliary space: O(n*m), as we are creating a new list of tuples with all possible combinations of the original tuples.

Method #3: Using enumerate function

Python3




test_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
 
 
res = [(tup1, tup2) for i, tup2 in test_list for j, tup1 in enumerate(i)]
print(res)


Output

[(1, 'gfg'), (2, 'gfg'), (3, 'gfg'), (5, 'cs'), (4, 'cs'), (3, 'cs')]

Time complexity: O(n^2) where n is the length of the longest list inside the tuples in test_list. 
Auxiliary space: O(n^2) where n is the length of the longest list inside the tuples in test_list.

Method #4: Using for loop

Python3




# Python3 code to demonstrate
# Combining tuples in list of tuples
 
# initializing list
test_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
 
# printing original list
print("The original list : " + str(test_list))
 
# Combining tuples in list of tuples
res = []
for i in test_list:
    a = []
    for j in i[0]:
        a.append((j, i[1]))
    res.extend(a)
 
# print result
print("The list tuple combination : " + str(res))


Output

The original list : [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
The list tuple combination : [(1, 'gfg'), (2, 'gfg'), (3, 'gfg'), (5, 'cs'), (4, 'cs'), (3, 'cs')]

Time Complexity: O(M*N)
Auxiliary Space: O(1)

Method #5 : Using chain.from_iterable() from the itertools module:

Python3




# import the chain function from the itertools module
from itertools import chain
 
# initialize the list of tuples
test_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
 
# print the original list
print("The original list : " + str(test_list))
 
# flatten the list of tuples using chain.from_iterable
# the inner generator expression generates a list of tuples for each inner list in the outer list
# each inner list is paired with the second element of the tuple, and the resulting list of tuples is flattened
res = list(chain.from_iterable(((y, x[1]) for y in x[0]) for x in test_list))
 
# print the resulting list of tuples
print("The list tuple combination : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy


Output

The original list : [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
The list tuple combination : [(1, 'gfg'), (2, 'gfg'), (3, 'gfg'), (5, 'cs'), (4, 'cs'), (3, 'cs')]

Time complexity: O(n) where n is number of elements in all tuples because it iterates through the elements in the list of tuples once. 
Auxiliary space: O(n) because it creates a new list to store the resulting tuples.

Method #6: Using reduce() function from functools module  +  list comprehension.

Python3




# Python3 code to demonstrate
# Combining tuples in list of tuples
from functools import reduce
 
# initializing list
test_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using reduce() + list comprehension
# Combining tuples in list of tuples
res = reduce(lambda x, y: x + [(i, y[1]) for i in y[0]], test_list, [])
 
# print result
print("The list tuple combination : " + str(res))


Output

The original list : [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
The list tuple combination : [(1, 'gfg'), (2, 'gfg'), (3, 'gfg'), (5, 'cs'), (4, 'cs'), (3, 'cs')]

Time complexity: O(n * m), where n is the length of the input list and m is the maximum length of a tuple in the input list.
Auxiliary space: O(n * m), where n is the length of the input list and m is the maximum length of a tuple in the input list.

Method #7: Using nested loops

  • Initialize an empty list to store the results.
  • Loop through each tuple in the test_list using a for loop, unpacking the first element of each tuple into a variable called i and the second element into a variable called tup2.
  • Within the first for loop, use another for loop to loop through each element in i.
  • Within the inner for loop, append a tuple to the results list containing the current element from i and tup2.
  • After both loops have completed, the results list will contain all combinations of elements from the tuples in the original list.

Python3




# Python3 code to demonstrate
# Combining tuples in list of tuples
# Using nested loops
 
# initializing list
test_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using nested loops
# Combining tuples in list of tuples
res = []
for i, tup2 in test_list:
    for tup1 in i:
        res.append((tup1, tup2))
 
# print result
print("The list tuple combination : " + str(res))


Output

The original list : [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')]
The list tuple combination : [(1, 'gfg'), (2, 'gfg'), (3, 'gfg'), (5, 'cs'), (4, 'cs'), (3, 'cs')]

Time complexity: O(n * m), where n is the length of the input list and m is the maximum length of a tuple in the input list.
Auxiliary space: O(n * m), where n is the length of the input list and m is the maximum length of a tuple in the input list.



Similar Reads

Python | Combining values from dictionary of list
Given a dictionary of list values, the task is to combine every key-value pair in every combination. Input : {"Name" : ["Paras", "Chunky"], "Site" : ["Geeksforgeeks", "Cyware", "Google"] } Output: [{'Site': 'Geeksforgeeks', 'Name': 'Paras'}, {'Site': 'Cyware', 'Name': 'Paras'}, {'Site': 'Google', 'Name': 'Paras'}, {'Site': 'Geeksforgeeks', 'Name':
2 min read
Python | Combining two sorted lists
Many times we encounter a problem where we wish to use the merge function of merge sort which is a classical problem that occurs many times while doing competitive programming. This type of problem when the own shorter and more compact ways to perform them are always quite handy. Let's discuss certain ways of combining two sorted lists in Python. M
7 min read
Python program to check whether number formed by combining all elements of the array is palindrome
Given an array arr[], the task is to combine all the elements in the array sequentially and check if it is a palindrome. Examples: Input: arr[] ={1 , 69 , 54 , 45 , 96 , 1} Output: palindrome Explanation: The number formed by combining all the elements is "1695445961" which is a palindrome Input: arr[] ={2 , 73 , 95 , 59 , 96 , 2} Output: not palin
4 min read
Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Remove tuples having duplicate first value from given list of tuples
Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. Examples: Input: [(12.121, 'Tuple1'), (12.121, 'Tuple2'), (12.121, 'Tuple3'), (923232.2323, 'Tuple4')] Output: [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]Input: [('Tuple1', 121), ('Tuple2', 125), ('Tuple1', 135), ('Tuple4', 478)]
7 min read
Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task. Method #1: Using Iteration C/C++ Code # Python code to count unique #
5 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this task can be performed. Method 1 (Using eval() + list
4 min read
Python - Filter all uppercase characters Tuples from given list of tuples
Given a Tuple list, filter tuples that contain all uppercase characters. Input : test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [('GFG', 'IS', 'BEST')] Explanation : Only 1 tuple has all uppercase Strings. Input : test_list = [("GFG", "iS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [
8 min read
Practice Tags :