Python | Modify Equal Tuple Rows
Last Updated :
16 May, 2023
Sometimes, while working with Python Records, we can have a problem in which we need to perform the modification of element records on equality of records. This can have a problem in domains that involve data. Let's discuss certain ways in which this task can be performed.
Input : test_list = [[(12, 5)], [(13, 2)], [(6, 7)]] test_row = [(13, 2)]
Output : [[(12, 5)], [(13, 8)], [(6, 7)]]
Input : test_list = [[(12, 5), (7, 6)]] test_row = [(13, 2)]
Output : [[(12, 5), (7, 6)]]
Method #1: Using loop + enumerate()
The combination of the above functions can be used to solve this problem. In this, we apply brute force for performing task of checking for equality and performing required modification.
Python3
# Python3 code to demonstrate working of
# Modify Equal Tuple Rows
# Using loop + enumerate()
# initializing list
test_list = [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing check row
test_row = [(12, 2), (13, 2)]
# Modify Equal Tuple Rows
# Using loop + enumerate()
# multiple y coordinate by 4
for idx, val in enumerate(test_list):
if val == test_row:
temp = []
for sub in val:
ele = (sub[0], sub[1] * 4)
temp.append(ele)
test_list[idx] = temp
# printing result
print("List after modification : " + str(test_list))
Output : The original list is : [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
List after modification : [[(12, 5), (13, 6)], [(12, 8), (13, 8)]]
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. loop + enumerate() performs n*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list.
Method #2: Using list comprehension
This is yet another way in which this task can be performed. In this, we perform the task using list comprehension in a one-liner way similar to the above method.
Python3
# Python3 code to demonstrate working of
# Modify Equal Tuple Rows
# Using list comprehension
# initializing list
test_list = [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing check row
test_row = [(12, 2), (13, 2)]
# Modify Equal Tuple Rows
# Using list comprehension
# multiple y coordinate by 4
res = [[(sub[0], sub[1] * 4) for sub in ele] if ele ==
test_row else ele for ele in test_list]
# printing result
print("List after modification : " + str(res))
Output : The original list is : [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
List after modification : [[(12, 5), (13, 6)], [(12, 8), (13, 8)]]
Method 3: Using the map() function with lambda function
- The program then applies the map() function, along with a lambda function, to modify the equal tuple rows in the "test_list" by multiplying the second element of the tuples by 4. The lambda function checks if the current sublist is equal to the "test_row" variable. If it is, then it applies a list comprehension to the sublist, which multiplies the second element of each tuple by 4, and returns the modified sublist. Otherwise, it returns the original sublist.
- The modified list is then stored in a variable named "res".
- Finally, the program prints the modified list using the print() function.
Python3
# Python3 code to demonstrate working of
# Modify Equal Tuple Rows
# Using map() + lambda function
# initializing list
test_list = [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing check row
test_row = [(12, 2), (13, 2)]
# Modify Equal Tuple Rows
# Using map() + lambda function
res = list(map(lambda ele: [(sub[0], sub[1] * 4)
for sub in ele] if ele == test_row else ele, test_list))
# printing result
print("List after modification : " + str(res))
OutputThe original list is : [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
List after modification : [[(12, 5), (13, 6)], [(12, 8), (13, 8)]]
Time complexity: O(nm) where n is the number of rows and m is the number of tuples in each row.
Auxiliary space: O(nm) for creating the new list of modified rows.
Method 4: Using the NumPy library.
Step-by-step approach:
- Import the NumPy library using the import statement.
- Convert the test_list to a NumPy array using the np.array() method.
- Use the np.where() method to compare each row of the NumPy array with the test_row.
- If the rows are equal, modify the second element of each tuple in the row using the np.multiply() method and the broadcasted test_row tuple.
- Convert the modified NumPy array back to a list of tuples using the np.ndarray.tolist() method.
Python3
import numpy as np
# initializing list
test_list = [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing check row
test_row = [(12, 2), (13, 2)]
# Using NumPy library
# Convert to numpy array
np_array = np.array(test_list)
# Use np.where() to compare rows with test_row
# If equal, modify the second element of each tuple in the row
# using np.multiply() and the broadcasted test_row tuple
np_array = np.where(np_array == np.array(test_row),
np.multiply(np_array, np.broadcast_to([1, 4], np_array.shape)),
np_array)
# Convert modified NumPy array back to a list of tuples
res = np_array.tolist()
# printing result
print("List after modification : " + str(res))
Output:
The original list is : [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
List after modification : [[[12, 5], [13, 6]], [[12, 8], [13, 8]]]
Time complexity: O(nm), where n is the number of sublists and m is the number of tuples in each sublist.
Auxiliary space: O(nm), as we create a NumPy array to store the list and perform element-wise comparisons and modifications on the NumPy array.
Similar Reads
Transpose Dual Tuple List in Python
Sometimes, while working with Python tuples, we can have a problem in which we need to perform tuple transpose of elements i.e, each column element of dual tuple becomes a row, a 2*N Tuple becomes N * 2 Tuple List. This kind of problem can have possible applications in domains such as web developmen
5 min read
Are Tuples Immutable in Python?
Yes, tuples are immutable in Python. This means that once a tuple is created its elements cannot be changed, added or removed. The immutability of tuples makes them a fixed, unchangeable collection of items. This property distinguishes tuples from lists, which are mutable and allow for modifications
2 min read
Remove empty tuples from a list - Python
The task of removing empty tuples from a list in Python involves filtering out tuples that contain no elements i.e empty. For example, given a list like [(1, 2), (), (3, 4), (), (5,)], the goal is to remove the empty tuples () and return a new list containing only non-empty tuples: [(1, 2), (3, 4),
3 min read
Tuples in Python
Python Tuple is a collection of objects separated by commas. A tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable.Python# Note : In case of list, we use squa
7 min read
Python | Pandas Series.equals()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.equals() function test whethe
3 min read
Create a List of Tuples in Python
The task of creating a list of tuples in Python involves combining or transforming multiple data elements into a sequence of tuples within a list. Tuples are immutable, making them useful when storing fixed pairs or groups of values, while lists offer flexibility for dynamic collections. For example
3 min read
Convert Tuple to List in Python
In Python, tuples and lists are commonly used data structures, but they have different properties:Tuples are immutable: their elements cannot be changed after creation.Lists are mutable: they support adding, removing, or changing elements.Sometimes, you may need to convert a tuple to a list for furt
2 min read
How to iterate through list of tuples in Python
In Python, a list of tuples is a common data structure used to store paired or grouped data. Iterating through this type of list involves accessing each tuple one by one and sometimes the elements within the tuple. Python provides several efficient and versatile ways to do this. Letâs explore these
2 min read
Python | Convert Numpy Arrays to Tuples
Given a numpy array, write a program to convert numpy array into tuples. Examples - Input: ([[1, 0, 0, 1, 0], [1, 2, 0, 0, 1]]) Output: ((1, 0, 0, 1, 0), (1, 2, 0, 0, 1)) Input: ([['manjeet', 'akshat'], ['nikhil', 'akash']]) Output: (('manjeet', 'akshat'), ('nikhil', 'akash')) Method #1: Using tuple
2 min read
Ways to shuffle a Tuple in Python
Shuffling numbers can sometimes prove to be a great help while programming practices. This process can be directly implemented on the data structures which are mutable like lists, but as we know that the tuples are immutable so it cannot be shuffled directly. If you'll try to do so as done in the be
2 min read