Python | Combining tuples in list of tuples
Last Updated :
21 Mar, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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
OutputThe 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))
OutputThe 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))
OutputThe 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 | 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 It
5 min read
Python - Join Tuples to Integers in Tuple List
Sometimes, while working with Python records, we can have a problem in which we need to concatenate all the elements, in order, to convert elements in tuples in List to integer. This kind of problem can have applications in many domains such as day-day and competitive programming. Let's discuss cert
5 min read
Swap tuple elements in list of tuples - Python
The task of swapping tuple elements in a list of tuples in Python involves exchanging the positions of elements within each tuple while maintaining the list structure. Given a list of tuples, the goal is to swap the first and second elements in every tuple. For example, with a = [(3, 4), (6, 5), (7,
3 min read
Unzip List of Tuples in Python
The task of unzipping a list of tuples in Python involves separating the elements of each tuple into individual lists, based on their positions. For example, given a list of tuples like [('a', 1), ('b', 4)], the goal is to generate two separate lists: ['a', 'b'] for the first elements and [1, 4] for
2 min read
Python - Convert List of Lists to Tuple of Tuples
Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let us discuss certain ways in which this task can be per
8 min read
Python | List of tuples to dictionary conversion
Interconversions are always required while coding in Python, also because of the expansion of Python as a prime language in the field of Data Science. This article discusses yet another problem that converts to dictionary and assigns keys as 1st element of tuple and rest as it's value. Let's discuss
3 min read
Python | Reverse each tuple in a list of tuples
Given a list of tuples, write a Python program to reverse each tuple in the given list of tuples. Examples: Input : [(1, 2), (3, 4, 5), (6, 7, 8, 9)] Output : [(2, 1), (5, 4, 3), (9, 8, 7, 6)] Input : [('a', 'b'), ('x', 'y'), ('m', 'n')] Output : [('b', 'a'), ('y', 'x'), ('n', 'm')] Method #1 : Nega
5 min read
Creating Sets of Tuples in Python
Tuples are an essential data structure in Python, providing a way to store ordered and immutable sequences of elements. When combined with sets, which are unordered collections of unique elements, you can create powerful and efficient data structures for various applications. In this article, we wil
3 min read
Generating a "Set Of Tuples" from A "List of Tuples" - Python
We are given a list of tuples and we need to extract only the unique tuples while removing any duplicates. This is useful in scenarios where you want to work with distinct elements from the list. For example:We are given this a list of tuples as [(1, 2), (3, 4), (1, 2), (5, 6)] then the output will
3 min read
Python | Convert list of tuples into digits
Given a list of tuples, the task is to convert it into list of all digits which exists in elements of list. Letâs discuss certain ways in which this task is performed. Method #1: Using re The most concise and readable way to convert list of tuple into list of all digits which exists in elements of l
6 min read