Python | Replace the tuple according to the Nth element of the tuple



Method # 1: Using loop + enumerate()
This task can be accomplished using a combination of loops and an enumeration function that can help access Nth element and then check and replace when the condition is met.

# Python3 code to demonstrate how it works
# Replace the tuple according to the Nth element of the tuple
# Using loops + enumerate ()

 
# Initializing list

test_list = [( `gfg` , 1 ), ( ` was` , 2 ), ( `best` , 3 )]

 
# print original list

print ( "The original list is:" + str (test_list))

 
# Initialize change recording

repl_rec = ( `is` , 2 )

 
# Initializing N

N = 1

 
# Replace the tuple according to the Nth element of the tuple
# Using loops + enumerate ()

for key, val in enumerate (test_list):

if val [N] = = repl_rec [N]:

test_list [key] = repl_rec

  break

  
# print 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)] 

Method # 2: Using List Comprehension
This is a one-line approach to solve this particular problem. In this we simply iterate over the list element and continue matching the corresponding Nth element of the tuple and performing the replacement.

# Python3 code to demonstrate how it works
# Replace the tuple according to the Nth element of the tuple
# Using the comprehension list

 
# Initializing list

test_list = [( `gfg` , 1 ), ( `was` , 2 ), ( `best` , )]

 
# print the original list

print ( " The original list is: " + str (test_list))

 
# Initialize a change record

repl_rec = ( `is` , 2 )

 
# Initialization N

N = 1

 
# Replace with rte according to the Nth element of the tuple
# Using the comprehension list

res = [repl_rec if sub [N] = = repl_rec [N] else sub for sub in test_list]

 
# print result

print ( "The tuple after replacement is:" + str (res))

Output:

 The origina l list is: [(`gfg`, 1), (` was`, 2), (`best`, 3)] The tuple after replacement is: [(` gfg`, 1), (`is`, 2 ), (`best`, 3)]