VOOZH about

URL: https://www.geeksforgeeks.org/python/python-adding-n-to-kth-tuple-element/

⇱ Python | Adding N to Kth tuple element - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python | Adding N to Kth tuple element

Last Updated : 23 Feb, 2023

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 can be performed. In this, we just iterate the list to change the Kth element by predefined value N in code. 


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

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

Method #2: Using list comprehension This method is having the same approach as the above method, just reduces lines of code using list comprehension functionality to make code compact by size. 


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

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

Auxiliary Space: O(n), as we are creating a new list to store the modified tuples.

Method #3: Using map() and lambda function
This method is an alternative to using loops and list comprehension, it uses the map function to iterate over the list and a lambda function to add N to the Kth element of each tuple.


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

Time complexity: O(n)
Auxiliary Space: O(n)

Comment