The Wayback Machine - https://web.archive.org/web/20241002022753/https://www.geeksforgeeks.org/python-update-each-element-in-tuple-list/
Open In App

Python | Update each element in tuple list

Last Updated : 18 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Sometimes, while working with data, we can have a problem in which we need to perform update operations on tuples. This can have applications across many domains such as web development. Let’s discuss certain ways in which this task can be performed in Python. 

Update List in Python

There are various ways to update a list in Python here, we are discussing some generally used methods for update list in Python which are the following.

Create List

In this example, the below code initializes a list of tuples called test_list and prints the original list. The list contains three tuples, each consisting of three elements.

Python3




# Python3 code to demonstrate working of
# Update each element in tuple list
# Using list comprehension
 
# initialize list
test_list = [(1, 3, 4), (2, 4, 6), (3, 8, 1)]
 
# printing original list
print("The original list :" + str(test_list))


Output :

The original list :[(1, 3, 4), (2, 4, 6), (3, 8, 1)]

Python program to update each element in the Tuple List using List Comprehension

This method is shorthand to brute function that can be applied to perform this task. In this, we iterate for each element of each tuple to perform a bulk update of data. 

Example : In this example the below Python code adds the value of `add_ele` (which is 4) to each element of tuples in the list `test_list` using list comprehension, and then prints the updated list `res`.

Python3




# initialize add element
add_ele = 4
 
# Update each element in tuple list
# Using list comprehension
res = [tuple(j + add_ele for j in sub ) for sub in test_list]
 
# printing result
print("List after bulk update : " + str(res))


Output:

List after bulk update : [(5, 7, 8), (6, 8, 10), (7, 12, 5)]

 Update each element in tuple list in Python using Map() + Lambda + List Comprehension

The combination of above functions can be used to perform this task. In this, we just iterate for all elements using map() and extend logic of update using lambda function. 

Example : In this example the below code updates each element in a list of tuples (`test_list`) by adding 4 to each element, using list comprehension, map(), and lambda functions. The result is stored in the ‘res’ list, and the updated list of tuples is printed.

Python3




# initialize add element
add_ele = 4
 
# Update each element in tuple list
# Using list comprehension + map() + lambda
res = [tuple(map(lambda ele : ele + add_ele, sub)) for sub in test_list]
 
# printing result
print("List after bulk update :" + str(res))


Output :

List after bulk update : [(5, 7, 8), (6, 8, 10), (7, 12, 5)]

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

Python program to update each element in the Tuple List using the Extend() Method

The extend() method is another way to update a list in Python. It allows you to append elements of an iterable (e.g., another list) to the end of the current list. This method is useful for adding multiple elements in a single operation.

Example : In this example the below code extends the list `test_list` by appending the elements from the `new_elements` tuple, and then prints the updated list.

Python3




# new elements to extend the list
new_elements = [(5, 7, 2), (6, 9, 3)]
 
# using extend() to update the list
test_list.extend(new_elements)
 
# printing the updated list
print("List after using extend() method : " + str(test_list))


Output :

List after using extend() method : [(1, 3, 4), (2, 4, 6), (3, 8, 1), (5, 7, 2), (6, 9, 3)]

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

Python Update a value in a list of Tuples using Slicing and Concatenation

Slicing and concatenation provide a concise way to update a list. You can use slicing to select a portion of the original list and concatenate it with new elements.

Example : In this example the below python code updates a list (`test_list`) by replacing elements at a specific index (`index_to_update`) with a tuple of new elements (`new_elements`) using slicing and concatenation, then prints the updated list.

Python3




# new elements to replace at a specific index
new_elements = (5, 7, 2)
 
# index to update
index_to_update = 1
 
# using slicing and concatenation to update the list
test_list = test_list[:index_to_update] + [new_elements] + test_list[index_to_update + 1:]
 
# printing the updated list
print("List after using slicing and concatenation : " + str(test_list))


Output :

List after using slicing and concatenation: [(1, 3, 4), (5, 7, 2), (3, 8, 1)]

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

Update List in Python Using enumerate() Method

Using the `enumerate()` method in Python to update a list involves iterating through the list with both the index and elements, enabling simultaneous access to the index and value. This allows for concise updates to the elements based on their index within the list.

Example : In this example the below provided Python code demonstrates the updating of each element in a tuple list using enumerate() and tuple unpacking. The test_list contains three tuples, each with three elementst. Then, a list comprehension is used along with enumerate() to iterate over the tuples in the list.

Python3




# Using Enumerate() Method
# Update each element by adding 1 to each value
updated_list = [(a + 1, b + 1, c + 1) for idx, (a, b, c) in enumerate(test_list)]
 
# printing result
print("The updated list using Enumerate() and Tuple Unpacking: " + str(updated_list))


Output :

The updated list using Enumerate() and Tuple Unpacking: [(2, 4, 5), (3, 5, 7), (4, 9, 2)]

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

Access each element of a Tuple using zip() Function

The method of updating a list in Python using the `zip()` function involves transposing the original list of tuples, allowing simultaneous iteration through corresponding elements. By applying list comprehension, each tuple’s elements can be updated based on the desired operation.

Example : in this example the below Python code updates each element in a tuple list using the Zip() function. It creates a new list by adding 1 to each value in the original tuple list. The updated list is then printed.

Python3




# Using Zip() + List Comprehension
# Update each element by adding 1 to each value
updated_list = [tuple(x + 1 for x in t) for t in zip(*test_list)]
 
# printing result
print("The updated list using Zip() function: " + str(updated_list))


Output :

The original list :[(1, 3, 4), (2, 4, 6), (3, 8, 1)]
The updated list using Zip() function: [(2, 4, 5), (3, 5, 7), (4, 9, 2)]

Time Complexity: O(n*m)
Space Complexity : O(n*m)

Access each element in a list in Python using a Loop And Tuple Unpacking

The function `update_tuples` modifies a list of tuples, replacing the first element in each tuple with a given new value. It iterates through the tuples, creating new tuples with the updated value, and replaces the original tuples. To demonstrate, a list ‘tuples’ and a new value ‘new_val’ are defined, and the function is called with these arguments, resulting in the updated list being printed.

Example : In this example the below code updates the first element of each tuple in the list tuples with the value new_val and returns the modified list. The output is a list with the first element of each tuple replaced by 5: [(5, 56, 'M'), (5, 14, 'F'), (5, 43, 'F'), (5, 10, 'M')]

Python3




def update_tuples(tuples, new_val):
    for i in range(len(tuples)):
        x, y, z = tuples[i]
        tuples[i] = (new_val, y, z)
    return tuples
 
tuples = [(1, 56, 'M'), (1, 14, 'F'), (2, 43, 'F'), (2, 10, 'M')]
new_val = 5
 
updated_tuples = update_tuples(tuples, new_val)
print(updated_tuples)


Output:

[(5, 56, 'M'), (5, 14, 'F'), (5, 43, 'F'), (5, 10, 'M')]

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

Update List in Python using For Loop

In this method the code iterates through each tuple in a list, converts it to a mutable list for updates, and transforms it back to a tuple. Updated tuples are then appended to a new list. The algorithm involves creating and populating a new list with the modified tuples by iterating over the original list.

Example : In this example the below code modifies the element at the specified index in each tuple within the list `test_list` to the value `5`, creating a new list `new_list` with the updated tuples. The result is then printed.

Python3




test_list = [(1, 3, 4), (2, 4, 6), (3, 8, 1)]
index = 1
value = 5
 
new_list = []
for tup in test_list:
    temp_list = list(tup)
    temp_list[index] = value
    new_tup = tuple(temp_list)
    new_list.append(new_tup)
 
print("Updated list:", new_list)


Output:

Updated list: [(1, 5, 4), (2, 5, 6), (3, 5, 1)]

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



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 | Replace tuple according to Nth tuple element
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
8 min read
Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple. Input: [(1, 3), (3, 2), (2, 1)] Output: [(2, 1), (3, 2), (1, 3)] Explanation: sort tuple based on the last digit of each tuple. Methods #1: Using sorted(). Sorted() method sorts a list and always returns a list with the elements in
7 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Python Program to Merge tuple list by overlapping mid tuple
Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read
Python program to create a list of tuples from given list having number and its cube in each tuple
Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number. Example: Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] Input: list = [9, 5, 6] Output: [(9, 729), (5, 125), (6, 216)] Method #1 : Using pow() function.We can use list compreh
5 min read
Python - Dictionary Tuple values update
Sometimes, while working with Tuple data, we can have problem when we perform its editions, reason being it's immutability. This discusses the editions in tuple values in dictionary. This can have application in many domains as dictionary is often popular data type in web development and Data Science domains. Let's discuss certain ways in which thi
3 min read
Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 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 this task can be performed. Input : test_tuple = ('A'
10 min read
Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set method is to convert other type values to set this meth
7 min read
Tuple within a Tuple in Python
In the realm of Python programming, tuples offer a flexible solution for organizing data effectively. By allowing the inclusion of other tuples within them, tuples further enhance their capabilities. In this article, we will see how we can use tuple within a tuple in Python. Using Tuple within a Tuple in PythonBelow are some of the ways by which we
4 min read
Python | Reverse each tuple in a list of tuples
Given a list of tuples, write a Python program to reverse each tuple in the given list of tuples. Examples: Input : [(1, 2), (3, 4, 5), (6, 7, 8, 9)] Output : [(2, 1), (5, 4, 3), (9, 8, 7, 6)] Input : [('a', 'b'), ('x', 'y'), ('m', 'n')] Output : [('b', 'a'), ('y', 'x'), ('n', 'm')] Method #1 : Negative-step slicing We can use standard negative-ste
5 min read
Python | Count the elements in a list until an element is a Tuple
In this problem, we need to accept a list. The list can have nested tuples. We need to count the elements in a list until a tuple has been encountered. Examples: Input : [4, 5, 6, 10, (1, 2, 3), 11, 2, 4] Output : 4 Input : [4, (5, 6), 10, (1, 2, 3), 11, 2, 4] Output : 1 Method #1: In this program we will use the concept of isinstance() to verify w
2 min read
Python | Remove duplicates based on Kth element tuple list
Sometimes, while working with records, we may have a problem in which we need to remove duplicates based on Kth element of a tuple in the list. This problem has application in domains that uses records as input. Let's discuss certain ways in which this problem can be solved. Method #1: Using loop This is a brute-force method to perform this particu
8 min read
Python | Minimum element in tuple list
Sometimes, while working with data in form of records, we can have a problem in which we need to find the minimum element of all the records received. This is a very common application that can occur in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using min() + generator expression This is the mos
5 min read
Python | Maximum element in tuple list
Sometimes, while working with data in form of records, we can have a problem in which we need to find the maximum element of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed. Method #1: Using max() + generator expression This is the most
6 min read
Python - Concatenate Kth element in Tuple List
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data in concatenated format. Lets discuss certain ways how one can achieve solutions to this problem. Method #
8 min read
Python - Find first element by second in tuple List
Sometimes, while working with Python records, we can have a problem in which we need to find the first element of tuple from the given second element. This kind of problem can occur in domains such as web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [(4, 5), (5, 6), (1, 3), (6, 6)] K = 6 Output :
4 min read
Python - Add K to Minimum element in Column Tuple List
Sometimes, while working with Tuple records, we can have a problem in which we need to perform task of adding certain element to max/ min element to each column of Tuple list. This kind of problem can have application in web development domain. Let's discuss a certain way in which this task can be performed. Input : test_list = [(4, 5), (3, 2), (2,
8 min read
Python - Test if greater than preceding element in Tuple List
Given list of tuples, check if preceding element is smaller than the current element for each element in Tuple list. Input : test_list = [(5, 1), (4, 9), (3, 5)] Output : [[False, False], [False, True], [False, True]] Explanation : First element always being False, Next element is checked for greater value. Input : test_list = [(1, 8), (2, 2), (3,
9 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 - Sort by Frequency of second element in Tuple List
Given list of tuples, sort by frequency of second element of tuple. Input : test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] Output : [(1, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)] Explanation : 7 occurs 3 times as 2nd element, hence all tuples with 7, are aligned first. Input : test_list = [(1, 7), (8, 7), (9, 8), (3, 7)] Output : [(
6 min read
Python - Check if any list element is present in Tuple
Given a tuple, check if any list element is present in it. Input : test_tup = (4, 5, 10, 9, 3), check_list = [6, 7, 10, 11] Output : True Explanation : 10 occurs in both tuple and list. Input : test_tup = (4, 5, 12, 9, 3), check_list = [6, 7, 10, 11] Output : False Explanation : No common elements. Method #1: Using loop In this, we keep a boolean v
6 min read
Python program to convert tuple into list by adding the given string after every element
Given a Tuple. The task is to convert it to List by adding the given string after every element. Examples: Input : test_tup = (5, 6, 7), K = "Gfg" Output : [5, 'Gfg', 6, 'Gfg', 7, 'Gfg'] Explanation : Added "Gfg" as succeeding element. Input : test_tup = (5, 6), K = "Gfg" Output : [5, 'Gfg', 6, 'Gfg'] Explanation : Added "Gfg" as succeeding element
5 min read
Python - Test if tuple list has Single element
Given a Tuple list, check if it is composed of only one element, used multiple times. Input : test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)] Output : True Explanation : All elements are equal to 3. Input : test_list = [(3, 3, 3), (3, 3), (3, 4, 3), (3, 3)] Output : False Explanation : All elements are not equal to any particular element. Method
8 min read
Python | Remove particular element from tuple list
Since the advent of the popularity of Python in data analysis, we have a list of tuples as a container in many of our problems. Sometimes, while data preprocessing, we might have a problem in which we need to completely remove a particular element from a list of tuples. Let's discuss a way in which this task can be performed. Removing element for t
7 min read
Python program to get the indices of each element of one list in another list
Given 2 lists, get all the indices of all occurrence of each element in list2 from list1. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 4] Output : [[3], [1, 9], [0, 7]] Explanation : 5 is present at 1st and 9th index. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 8] Output : [[3], [1, 9],
7 min read
Practice Tags :