Open In App

Python | Replace tuple according to Nth tuple element

Last Updated : 03 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it’s application in web development domain. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using loop + enumerate() This task can be performed using the combination of loops and enumerate function which can help to access the Nth element and then check and replace when the condition is satisfied. 

Python3




# Python3 code to demonstrate working of
# Replace tuple according to Nth tuple element
# Using loops + enumerate()
 
# Initializing list
test_list = [('gfg', 1), ('was', 2), ('best', 3)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing change record
repl_rec = ('is', 2)
 
# Initializing N
N = 1
 
# Replace tuple according to Nth tuple element
# Using loops + enumerate()
for key, val in enumerate(test_list):
    if val[N] == repl_rec[N]:
        test_list[key] = repl_rec
        break
 
# printing result
print("The tuple after replacement is : " + str(test_list))


Output

The original list is : [('gfg', 1), ('was', 2), ('best', 3)]
The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2: Using list comprehension This is the one-liner approach to solve this particular problem. In this, we just iterate the list element and keep matching the matching Nth element of tuple and perform replacement. 

Python3




# Python3 code to demonstrate working of
# Replace tuple according to Nth tuple element
# Using list comprehension
 
# Initializing list
test_list = [('gfg', 1), ('was', 2), ('best', 3)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing change record
repl_rec = ('is', 2)
 
# Initializing N
N = 1
 
# Replace tuple according to Nth tuple element
# Using list comprehension
res = [repl_rec if sub[N] == repl_rec[N] else sub for sub in test_list]
 
# printing result
print("The tuple after replacement is : " + str(res))


Output

The original list is : [('gfg', 1), ('was', 2), ('best', 3)]
The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), as we are creating a new list to store the result.

Method #3 : Using the map() function

This method uses the map() function to check and replace the element that matches the condition.

Python3




# Python3 code to demonstrate working of
# Replace tuple according to Nth tuple element
# Using map()
 
# Initializing list
test_list = [('gfg', 1), ('was', 2), ('best', 3)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing change record
repl_rec = ('is', 2)
 
# Initializing N
N = 1
 
# Replace tuple according to Nth tuple element
# Using map()
res = list(map(lambda x: repl_rec if x[N] == repl_rec[N] else x, test_list))
 
# printing result
print("The tuple after replacement is : " + str(res))
 
# Output:
# The original list is : [('gfg', 1), ('was', 2), ('best', 3)]
# The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list is : [('gfg', 1), ('was', 2), ('best', 3)]
The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]

Time complexity: O(n), as it iterates through the list of tuples once.
Auxiliary space: O(n) as it creates a new list to store the modified tuples, the size of this list is equal to the size of the original list.

Method #4:  Use the filter() function along with a lambda function 

The filter() function is used to remove the tuples from test_list that don’t match the value of the Nth element in repl_rec. The resulting map object is converted to a list using the list() function. Then, the repl_rec tuple is added to the list using the concatenation operator +. The resulting list contains the tuples with the replaced value.

Python3




test_list = [('gfg', 1), ('was', 2), ('best', 3)] # initializing list
repl_rec = ('is', 2) # initializing change record
N = 1 # initializing N
 
# using filter function with lambda to remove tuples that don't match value of Nth element, and then adding repl_rec tuple to the list
test_list = list(filter(lambda x: x[N] != repl_rec[N], test_list)) + [repl_rec]
 
print("The tuple after replacement is : " + str(test_list)) # printing result


Output

The tuple after replacement is : [('gfg', 1), ('best', 3), ('is', 2)]

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), where n is the number of tuples in the list.

Method #5: Using a simple loop.

  • Define a list of tuples test_list containing three tuples.
  • Define a tuple repl_rec to use as a replacement.
  • Create a new list res by iterating over each tuple in test_list.
  • For each tuple x in test_list, use a ternary expression to check if the second element of x is equal to 2. If it is, replace x with repl_rec, otherwise keep x as it is.
  • Print the updated list res containing the original tuples with the specified replacement tuple.

Python3




test_list = [('gfg', 1), ('was', 2), ('best', 3)]
repl_rec = ('is', 2)
N = 1
 
# Create an empty list to store the updated tuples
res = []
 
# Iterate over each tuple in the original list
for x in test_list:
    # Check if the Nth element of the tuple matches the Nth element of the replacement tuple
    if x[N] == repl_rec[N]:
        # If it matches, add the replacement tuple to the result list
        res.append(repl_rec)
    else:
        # If it doesn't match, add the original tuple to the result list
        res.append(x)
 
# Print the updated list of tuples
print("The tuple after replacement is : " + str(res))


Output

The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), where n is the number of tuples in the list.

Method #6: Using itertools.starmap().

Step-by-step approach:

  1. Initialize the list of tuples and the replacement tuple.
  2. Use itertools.starmap() method to iterate over each tuple in the original list.
  3. Use lambda function to check if the Nth element of the current tuple is equal to the Nth element of the replacement tuple.
  4. If the elements are equal, return the replacement tuple, else return the current tuple.
  5. Convert the iterator returned by starmap() to a list and store it in res.
  6. Print the updated list of tuples.

Python3




import itertools
 
# Initializing list
test_list = [('gfg', 1), ('was', 2), ('best', 3)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing change record
repl_rec = ('is', 2)
  
# Initializing N
N = 1
 
res = list(itertools.starmap(lambda *x: repl_rec if x[N] == repl_rec[N] else x, test_list))
 
 
# printing result
print("The tuple after replacement is : " + str(res))


Output

The original list is : [('gfg', 1), ('was', 2), ('best', 3)]
The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]

Time Complexity: O(n), The time complexity of the lambda function and the starmap() method is O(1) as they execute for each tuple in the list. Therefore, the overall time complexity is O(n), where n is the number of tuples in the list.
Auxiliary Space: O(n) as we create a new list to store the updated tuples.

Method #7: Using reduce() function from functools module

  • Import the functools module to use the reduce() function.
  • Define a lambda function to iterate over the original list and compare the Nth element of each tuple with that of the replacement tuple.
  • If they match, append the replacement tuple to the result list.
  • If they don’t match, append the original tuple to the result list.
  • Use the reduce() function with the lambda function and the initial value of an empty list to obtain the updated list of tuples.
  • Print the updated list of tuples.

Python3




import functools
 
test_list = [('gfg', 1), ('was', 2), ('best', 3)]
repl_rec = ('is', 2)
N = 1
 
# Define a lambda function to update the list of tuples
update_list = lambda res, x: res + [repl_rec] if x[N] == repl_rec[N] else res + [x]
 
# Use reduce() function with lambda function and initial value of an empty list to update the list of tuples
res = functools.reduce(update_list, test_list, [])
 
# Print the updated list of tuples
print("The tuple after replacement is : " + str(res))


Output

The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.



Similar Reads

Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python | Counting Nth tuple element
Sometimes, while working with Python, we can have a problem in which we need to count the occurrence of a particular's elements. This kind of problem is quite common while working with records. Let's discuss a way in which this task can be performed. Method #1 : Using Counter() + generator expression The combination of above functionalities can be
5 min read
Python - Extract Kth element of every Nth tuple in List
Given list of tuples, extract Kth column element of every Nth tuple. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)], K = 2, N = 3 Output : [3, 8, 10] Explanation : From 0th, 3rd, and 6th tuple, 2nd elements are 3, 8, 10. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6,
8 min read
Python | Remove Consecutive tuple according to key
Sometimes, while working with Python list, we can have a problem in which we can have a list of tuples and we wish to remove them basis of first element of tuple to avoid it's consecutive duplication. Let's discuss certain way in which this problem can be solved. Method : Using groupby() + itemgetter() + next() This task can be performed using comb
5 min read
Python program to replace every Nth character in String
Given a string, the task is to write a Python program to replace every Nth character in a string by the given value K. Examples: Input : test_str = "geeksforgeeks is best for all geeks", K = '$', N = 5 Output : geeks$orge$ks i$ bes$ for$all $eeks Explanation : Every 5th character is converted to $. Input : test_str = "geeksforgeeks is best for all
5 min read
replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Python | Insert Nth element to Kth element in other list
Sometimes, while working with Python list, there can be a problem in which we need to perform the inter-list shifts of elements. Having a solution to this problem is always very useful. Let’s discuss the certain way in which this task can be performed. Method 1: Using pop() + insert() + index() This particular task can be performed using a combinat
9 min read
Python | Minimum K records of Nth index in tuple list
Sometimes, while working with data, we can have a problem in which we need to get the minimum of elements filtered by the Nth element of record. This has a very important utility in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using filter() + lambda + set() + list comprehension The combination
9 min read
Python | Nth tuple index Subtraction by K
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Let’s discuss certain ways in which K can be subtracted to Nth element of tuple in list. Method #1 : Using loop Using loops this task can be performed. In this, we just iterate the
6 min read
Practice Tags :
three90RightbarBannerImg