Open In App

Python | Update each element in tuple list

Last Updated : 18 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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
Practice Tags :