Python | Adding N to an element of a Kth tuple



Method # 1: Using a Loop
Loops can accomplish this task. In this, we simply iterate over the list to change the Kth element to the predefined N in the code.

# Python3 code to demonstrate how it works
# Adding N to the Kth tuple element
# Using a loop

  
# Initializing list

test_list = [( 4 , 5 , 6 ), ( 7 , 4 , 2 ), ( 9 , 10 , 11 )]

 
# print the original list

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

 
# Initialization N

N = 3  

  
# Initialize K

K = 1

 
# Add N to element of Kth tuple # Using a loop

res = []

for i in range ( 0 , len (test_list)):

res.append ((test_list [i] [ 0 ], test_list [i] [K] + N, test_list [i] [ 2 ]))

 
# print result

print ( "The tuple after adding N to Kth element:" + str (res))

Output:

 The original list is: [(4, 5, 6) , (7, 4, 2), (9, 10, 11)] The tuple after adding N to Kth element: [(4, 8, 6), (7, 7, 2), (9, 13, 11) ] 

Method # 2: Using a List Comprehension
This method takes the same approach as the previous method, just shortening lines of code using list comprehension functionality to keep the code compact.

# Python3 code to demonstrate how it works
# Adding N to the Kth tuple element
# Using the comprehension list

 
# Initializing list

test_list = [( 4 , 5 , 6 ), ( 7 , 4 , 2 ), ( 9 , 10 , 11 )]

  
# print original list

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

  
# Initializing N

N = 3  

 
# Initializing K

K = 1

  
# Adding N to the Kth tuple element
# Using comprehension list

res = [(a, b + N, c) for a, b, c in test_list]

 
# print result

print ( "The tuple after adding N to Kth element:" + str (res))

Output:

 The original list is: [(4, 5, 6), (7, 4, 2), (9, 10, 11)] The tuple after adding N to Kth element: [(4, 8, 6), (7, 7, 2), (9, 13, 11)]