Python – Maximum value in record list as tuple attribute
Last Updated :
11 May, 2023
Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the max of a list as a tuple attribute. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + max()
This particular problem can be solved using list comprehension combined with the max function in which we use max function to find the max of list as a tuple attribute and list comprehension to iterate through the list.
Python3
test_list = [( 'key1' , [ 3 , 4 , 5 ]), ( 'key2' , [ 1 , 4 , 2 ]), ( 'key3' , [ 9 , 3 ])]
print ( "The original list : " + str (test_list))
res = [(key, max (lst)) for key, lst in test_list]
print ( "The list tuple attribute maximum is : " + str (res))
|
Output :
The original list : [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
The list tuple attribute maximum is : [('key1', 5), ('key2', 4), ('key3', 9)]
Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a list with m * n keys and a list of m * n elements
Method #2: Using map + lambda + max()
The above problem can also be solved using the map function to extend the logic to the whole list and max function can perform a similar task as the above method.
Python3
test_list = [( 'key1' , [ 3 , 4 , 5 ]), ( 'key2' , [ 1 , 4 , 2 ]), ( 'key3' , [ 9 , 3 ])]
print ( "The original list : " + str (test_list))
res = list ( map ( lambda x: (x[ 0 ], max (x[ 1 ])), test_list))
print ( "The list tuple attribute maximum is : " + str (res))
|
Output :
The original list : [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
The list tuple attribute maximum is : [('key1', 5), ('key2', 4), ('key3', 9)]
Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a list with m * n keys and a list of m * n elements
Method #3 : Using sort() method
Python3
test_list = [( 'key1' , [ 3 , 4 , 5 ]), ( 'key2' , [ 1 , 4 , 2 ]), ( 'key3' , [ 9 , 3 ])]
print ( "The original list : " + str (test_list))
res = []
for i in test_list:
b = i[ 1 ]
b.sort()
res.append((i[ 0 ], b[ - 1 ]))
print ( "The list tuple attribute maximum is : " + str (res))
|
Output
The original list : [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
The list tuple attribute maximum is : [('key1', 5), ('key2', 4), ('key3', 9)]
Time Complexity: O(M*N*log (N)), where M and N are the length of list and maximum size of tuples in the list respectively.
Auxiliary Space: O(M)
Method #4: Using a for loop
Approach:
- Initialize an empty list to store the result.
- Iterate over the input list test_list using a for loop.
- For each tuple in the list, extract the key and list values.
- Find the maximum value in the list using the max() function.
- Create a new tuple with the key and maximum value.
- Append this tuple to the result list.
- Return the result list.
Below is the implementation of the above approach:
Python3
test_list = [( 'key1' , [ 3 , 4 , 5 ]), ( 'key2' , [ 1 , 4 , 2 ]), ( 'key3' , [ 9 , 3 ])]
print ( "The original list : " + str (test_list))
res = []
for key, lst in test_list:
max_val = max (lst)
res.append((key, max_val))
print ( "The list tuple attribute maximum is : " + str (res))
|
Output
The original list : [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
The list tuple attribute maximum is : [('key1', 5), ('key2', 4), ('key3', 9)]
Time complexity: O(n), where n is the length of the input list
Auxiliary space: O(n), for storing the result list
Method #5: Using the built-in function map() with max()
This method uses map() to apply the max() function to each list in the input list of tuples, and creates a new list of tuples with the maximum value for each list.
Python3
test_list = [( 'key1' , [ 3 , 4 , 5 ]), ( 'key2' , [ 1 , 4 , 2 ]), ( 'key3' , [ 9 , 3 ])]
print ( "The original list : " + str (test_list))
res = list ( map ( lambda x: (x[ 0 ], max (x[ 1 ])), test_list))
print ( "The list tuple attribute maximum is : " + str (res))
|
Output
The original list : [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
The list tuple attribute maximum is : [('key1', 5), ('key2', 4), ('key3', 9)]
Time complexity: O(n log n) due to the sort() method used in max().
Auxiliary space: O(n) for the output list.
METHOD 6:Using merge sort
APPROACH:
This program sorts a list of tuples based on the last value of each tuple in descending order using the merge sort algorithm. Then, it extracts the maximum value from each tuple in the sorted list and stores it in a new list of tuples.
ALGORITHM:
1.Define a merge_sort function that accepts the list to be sorted, a key function to extract the sort key from each element, and a reverse flag to indicate whether to sort in descending order.
2.If the length of the list is less than or equal to 1, return the list as is.
3.Find the middle index of the list and recursively sort the left and right halves using the merge_sort function.
4.Define a merge function that accepts the left and right halves and merges them into a single sorted list using the sort key and reverse flag.
5.Initialize an empty result list and two index variables i and j to 0.
6.While both i and j are less than the length of the left and right halves, respectively, compare the sort key values of the left and right halves at positions i and j using the reverse flag to determine the sorting order. If the left value is greater (in descending order) or less (in ascending order), append it to the result list and increment i. Otherwise, append the right value and increment j.
7.Append any remaining elements from the left or right half to the result list.
8.Return the result list.
9.Define the original list of tuples.
10.Sort the list in descending order based on the last value of each tuple using the merge_sort function with a lambda function as the key to extract the last value.
11.Extract the maximum value from each tuple in the sorted list using a list comprehension and the max() function.
12.Store the results in a new list of tuples.
13Print the original list and the list of tuples with the maximum value for each tuple.
Python3
def merge_sort(arr, key = None , reverse = False ):
if len (arr) < = 1 :
return arr
mid = len (arr) / / 2
left = merge_sort(arr[:mid], key = key, reverse = reverse)
right = merge_sort(arr[mid:], key = key, reverse = reverse)
return merge(left, right, key = key, reverse = reverse)
def merge(left, right, key = None , reverse = False ):
result = []
i = j = 0
while i < len (left) and j < len (right):
if key:
left_val = key(left[i])
right_val = key(right[j])
else :
left_val = left[i]
right_val = right[j]
if (reverse and left_val > right_val) or ( not reverse and left_val < right_val):
result.append(left[i])
i + = 1
else :
result.append(right[j])
j + = 1
result + = left[i:]
result + = right[j:]
return result
original_list = [( 'key1' , [ 3 , 4 , 5 ]), ( 'key2' , [ 1 , 4 , 2 ]), ( 'key3' , [ 9 , 3 ])]
sorted_list = merge_sort(original_list, key = lambda x: x[ 1 ][ - 1 ], reverse = True )
max_values_list = [(t[ 0 ], max (t[ 1 ])) for t in sorted_list]
print ( "Original List:" , original_list)
print ( "List tuple attribute maximum is:" , max_values_list)
|
Output
Original List: [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
List tuple attribute maximum is: [('key1', 5), ('key3', 9), ('key2', 4)]
Time complexity:
The time complexity of merge sort is O(n log n) in the average and worst cases, where n is the length of the list. The time complexity of finding the maximum value of each tuple is O(n), where n is the length of the list. Therefore, the overall time complexity of the program is O(n log n).
Space complexity:
The space complexity of merge sort is O(n), where n is the length of the list. The space complexity of storing the maximum values in a new list of tuples is also O(n). Therefore, the overall space complexity of the program is O(n).
Similar Reads
Python - Minimum in tuple list value
Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the minimum of list as tuple attribute. Letâs discuss certai
5 min read
Python - Records Maxima in List of Tuples
Sometimes, while working with records, we can have a problem in which we need to the maximum all the columns of a container of lists that are tuples. This kind of application is common in the web development domain. Letâs discuss certain ways in which this task can be performed. Method #1 : Using ma
5 min read
Python - List lengths as record attribute
Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the lengths of list as tuple attribute. Letâs discuss certai
3 min read
Python - Maximum record value key in dictionary
Sometimes, while working with dictionary records, we can have a problem in which we need to find the key with maximum value of a particular key of nested records in list. This can have applications in domains such as web development and Machine Learning. Lets discuss certain ways in which this task
6 min read
Python | Min and Max value in list of tuples
The task of finding the minimum and maximum values in a list of tuples in Python involves identifying the smallest and largest elements from each position (column) within the tuples. For example, given [(2, 3), (4, 7), (8, 11), (3, 6)], the first elements (2, 4, 8, 3) have a minimum of 2 and a maxim
3 min read
Python - Find minimum k records from tuple list
Sometimes, while working with data, we can have a problem in which we have records and we require to find the lowest K scores from it. This kind of application is popular in web development domain. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using sorted() + lambda Th
6 min read
Python | Get first element with maximum value in list of tuples
In Python, we can bind structural information in form of tuples and then can retrieve the same. But sometimes we require the information of tuple corresponding to maximum value of other tuple indexes. This functionality has many applications such as ranking. Let's discuss certain ways in which this
4 min read
Python - Extract Item with Maximum Tuple Value
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract the item with maximum value of value tuple index. This kind of problem can have application in domains such as web development. Let's discuss certain ways in which this task can be performed. Input :
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: U
6 min read
Python | Index minimum value Record
In Python, we can bind structural information in the form of tuples and then can retrieve the same, and has manyfold applications. But sometimes we require the information of a tuple corresponding to a minimum value of another tuple index. This functionality has many applications such as ranking. Le
4 min read