Python | Replace tuple according to Nth tuple element
Last Updated :
03 May, 2023
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
test_list = [( 'gfg' , 1 ), ( 'was' , 2 ), ( 'best' , 3 )]
print ( "The original list is : " + str (test_list))
repl_rec = ( 'is' , 2 )
N = 1
for key, val in enumerate (test_list):
if val[N] = = repl_rec[N]:
test_list[key] = repl_rec
break
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
test_list = [( 'gfg' , 1 ), ( 'was' , 2 ), ( 'best' , 3 )]
print ( "The original list is : " + str (test_list))
repl_rec = ( 'is' , 2 )
N = 1
res = [repl_rec if sub[N] = = repl_rec[N] else sub for sub in test_list]
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
test_list = [( 'gfg' , 1 ), ( 'was' , 2 ), ( 'best' , 3 )]
print ( "The original list is : " + str (test_list))
repl_rec = ( 'is' , 2 )
N = 1
res = list ( map ( lambda x: repl_rec if x[N] = = repl_rec[N] else x, test_list))
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), 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 )]
repl_rec = ( 'is' , 2 )
N = 1
test_list = list ( filter ( lambda x: x[N] ! = repl_rec[N], test_list)) + [repl_rec]
print ( "The tuple after replacement is : " + str (test_list))
|
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
res = []
for x in test_list:
if x[N] = = repl_rec[N]:
res.append(repl_rec)
else :
res.append(x)
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:
- Initialize the list of tuples and the replacement tuple.
- Use itertools.starmap() method to iterate over each tuple in the original list.
- Use lambda function to check if the Nth element of the current tuple is equal to the Nth element of the replacement tuple.
- If the elements are equal, return the replacement tuple, else return the current tuple.
- Convert the iterator returned by starmap() to a list and store it in res.
- Print the updated list of tuples.
Python3
import itertools
test_list = [( 'gfg' , 1 ), ( 'was' , 2 ), ( 'best' , 3 )]
print ( "The original list is : " + str (test_list))
repl_rec = ( 'is' , 2 )
N = 1
res = list (itertools.starmap( lambda * x: repl_rec if x[N] = = repl_rec[N] else x, test_list))
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
update_list = lambda res, x: res + [repl_rec] if x[N] = = repl_rec[N] else res + [x]
res = functools. reduce (update_list, test_list, [])
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 | Adding N to Kth tuple element
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 N can be added to Kth element of tuple in list. Method #1 : Using loop Using loops this task c
3 min read
Python - Sort Tuple List by Nth Element of Tuple
We are given list of tuple we need to sort tuple by Nth element of each tuple. For example d = [(1, 5), (3, 2), (2, 8), (4, 1)] and k=1 we need to sort by 1st element of each tuple so that output for given list should be [(4, 1), (3, 2), (1, 5), (2, 8)] Using sorted() with lambdasorted() function wi
3 min read
Python | Count the elements till first tuple
AuxiliSometimes, while working with records, we can have a problem in which an element of a record is another tuple records and we might have to count the element count that occur before the record. This is a problem that does not occur commonly, but having a solution to it is useful. Let's discuss
4 min read
Python - Row-wise element Addition in Tuple Matrix
Sometimes, while working with Python tuples, we can have a problem in which we need to perform Row-wise custom elements addition in Tuple matrix. This kind of problem can have application in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [[('Gfg', 3
4 min read
Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which thi
10 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
Python - Flatten tuple of List to tuple
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
Python | Extend tuples by count of elements in tuple
Sometimes, while working with data, we can have an application in which we need to duplicate tuple elements by the amount of element count. This is very unique application but can occur in certain cases. Let's discuss certain ways in which this task can be performed. Method #1: Using nested loops Th
6 min read
Getting an Element from Tuple of Tuples in Python
Tuples in Python are versatile data structures that allow you to store and organize collections of elements. When dealing with tuples of tuples, accessing specific elements becomes essential for effective data manipulation. In this article, we'll explore some different methods to retrieve elements f
2 min read
How To Slice A List Of Tuples In Python?
In Python, slicing a list of tuples allows you to extract specific subsets of data efficiently. Tuples, being immutable, offer a stable structure. Use slicing notation to select ranges or steps within the list of tuples. This technique is particularly handy when dealing with datasets or organizing i
3 min read