Python | Modifying tuple contents with list
Last Updated :
22 Mar, 2023
In Python, tuples are immutable and hence no changes are required in them once they are formed. This restriction makes their processing harder and hence certain operations on tuples are quite useful to have knowledge of. This article deals with modifying the second tuple element with the list given. Let's discuss certain ways in which this can be done.
Method #1: Using for loop
Python3
# Python3 code to demonstrate
# modifying tuple elements
# initializing lists
test_list1 = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
test_list2 = [4, 5, 6]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# modifying tuple elements
res=[]
for i in range(0,len(test_list1)):
x=(test_list1[i][0],test_list2[i])
res.append(x)
# print result
print("The modified resultant list of tuple : " + str(res))
OutputThe original list 1 : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The original list 2 : [4, 5, 6]
The modified resultant list of tuple : [('Geeks', 4), ('for', 5), ('Geeks', 6)]
Time Complexity: O(N), where N is the length of the input lists test_list1 and test_list2.
Auxiliary Space: O(N)
Method #2: Using zip() + list comprehension
In this method, we just take the first element of list of tuple and the element at corresponding index and zip them together using the zip function.
Python3
# Python3 code to demonstrate
# modifying tuple elements
# using zip() + list comprehension
# initializing lists
test_list1 = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
test_list2 = [4, 5, 6]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using zip() + list comprehension
# modifying tuple elements
res = [(i[0], j) for i, j in zip(test_list1, test_list2)]
# print result
print("The modified resultant list of tuple : " + str(res))
Output : The original list 1 : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The original list 2 : [4, 5, 6]
The modified resultant list of tuple : [('Geeks', 4), ('for', 5), ('Geeks', 6)]
Method #3: Using zip() + map() + operator.itemgetter()
The itemgetter function here does the task of fetching the constant of two tuple elements which is then mapped with the corresponding index using the map function. The zip function is used to extend this logic to the entire list.
Python3
# Python3 code to demonstrate
# modifying tuple elements
# using zip() + map() + operator.itemgetter()
import operator
# initializing lists
test_list1 = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
test_list2 = [4, 5, 6]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using zip() + map() + operator.itemgetter()
# modifying tuple elements
temp = map(operator.itemgetter(0), test_list1)
res = list(zip(temp, test_list2))
# print result
print("The modified resultant list of tuple : " + str(res))
Output : The original list 1 : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The original list 2 : [4, 5, 6]
The modified resultant list of tuple : [('Geeks', 4), ('for', 5), ('Geeks', 6)]
Method #4: Using for itertools module:
The itertools.zip_longest() function is used to iterate through two lists test_list1 and test_list2 simultaneously. For each iteration, it creates a tuple (tup1, tup2) where tup1 is an element from test_list1 and tup2 is an element from test_list2.
The resulting list res is created using a list comprehension that iterates through the tuples produced by itertools.zip_longest(). For each iteration, it creates a new tuple with the first element of tup1 and the second element of tup2. The resulting list res contains the modified tuples.
Here is an example using the itertools module:
Python3
import itertools
# Initializing lists
test_list1 = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
test_list2 = [4, 5, 6]
# Printing original lists
print("The original list 1:", test_list1)
print("The original list 2:", test_list2)
# Modifying tuple elements using itertools.zip_longest()
res = [(tup1[0], tup2) for tup1, tup2 in itertools.zip_longest(test_list1, test_list2)]
# Print result
print("The modified resultant list of tuple:", res)
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list 1: [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The original list 2: [4, 5, 6]
The modified resultant list of tuple: [('Geeks', 4), ('for', 5), ('Geeks', 6)]
Time complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using enumerate
In this example, the modify_tuples function takes in two arguments: list1, which is the list of tuples to be modified, and list2, which is the list of values to be used for modification. The function loops through each tuple in list1, and uses the enumerate function to get both the index and the values of each tuple. The function then creates a new tuple with the same first value as the original tuple, and the corresponding value from list2. The function appends the new tuple to a result list. Finally, the function returns the result list containing the modified tuples.
Python3
def modify_tuples(list1, list2):
# Create an empty list to store the modified tuples.
result = []
# Loop through each tuple in the first list.
for i, (x, y) in enumerate(list1):
# Get the i-th value from the second list, and use it to modify the y value in the current tuple.
result.append((x, list2[i]))
# Return the list of modified tuples.
return result
list1 = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
list2 = [4, 5, 6]
result = modify_tuples(list1, list2)
print(result)
Output[('Geeks', 4), ('for', 5), ('Geeks', 6)]
Time complexity: O(n)
Auxiliary Space: O(n)
Method #6: Using map() and lambda function:
Algorithm:
1.Initialize two lists, test_list1 and test_list2.
2.Print the original lists.
3.Use the map() and lambda function to modify the tuple elements.
4.The lambda function extracts the first element from the tuple in test_list1 and combines it with the corresponding 5.element from test_list2 to form a new tuple.
6.Convert the result of the map() function into a list.
7.Print the modified resultant list of tuple.
Python3
# initializing lists
test_list1 = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
test_list2 = [4, 5, 6]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using map() and lambda function to modify tuple elements
res = list(map(lambda x, y: (x[0], y), test_list1, test_list2))
# print result
print("The modified resultant list of tuple : " + str(res))
#This code is contributed by Jyothi pinjala
OutputThe original list 1 : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The original list 2 : [4, 5, 6]
The modified resultant list of tuple : [('Geeks', 4), ('for', 5), ('Geeks', 6)]
Time Complexity:
The time complexity of this algorithm is O(n), where n is the length of the lists test_list1 and test_list2. The map() function has a time complexity of O(n), as it needs to iterate over each element of the lists. The lambda function is a constant time operation, so it does not affect the overall time complexity.
Auxiliary Space:
The space complexity of this algorithm is also O(n), as we are creating a new list to store the modified tuples. The size of the new list will be equal to the length of the input lists, so the space complexity is linear with respect to the input size.
Similar Reads
Python | Convert list of tuples into list
In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
3 min read
Python - Cross Pairing in Tuple List
Given 2 tuples, perform cross pairing of corresponding tuples, convert to single tuple if 1st element of both tuple matches. Input : test_list1 = [(1, 7), (6, 7), (8, 100), (4, 21)], test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)] Output : [(7, 3)] Explanation : 1 occurs as tuple element at pos. 1 in
5 min read
Python - Convert a list into tuple of lists
When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists.For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this con
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
Flatten tuple of List to tuple - Python
The task of flattening a tuple of lists to a tuple in Python involves extracting and combining elements from multiple lists within a tuple into a single flattened tuple. For example, given tup = ([5, 6], [6, 7, 8, 9], [3]), the goal is to flatten it into (5, 6, 6, 7, 8, 9, 3). Using itertools.chain(
3 min read
How to Modify a List While Iterating in Python
Modifying a list while iterating can be tricky but there are several ways to do it safely. One simple way to modify a list while iterating is by using a for loop with the index of each item. This allows us to change specific items at certain positions.Pythona = [1, 2, 3, 4] for i in range(len(a)): i
2 min read
Python | Combining tuples in list of tuples
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
7 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
Print a List of Tuples in Python
The task of printing a list of tuples in Python involves displaying the elements of a list where each item is a tuple. A tuple is an ordered collection of elements enclosed in parentheses ( ), while a list is an ordered collection enclosed in square brackets [ ].Using print()print() function is the
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