# Python – Maximum value in record list as tuple 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 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

 `# Python3 code to demonstrate``# Records element list Maximum``# using list comprehension + max()` `# initializing list``test_list ``=` `[(``'key1'``, [``3``, ``4``, ``5``]), (``'key2'``, [``1``, ``4``, ``2``]), (``'key3'``, [``9``, ``3``])]` `# printing original list``print``(``"The original list : "` `+` `str``(test_list))` `# using list comprehension + max()``# Records element list Maximum``res ``=` `[(key, ``max``(lst)) ``for` `key, lst ``in` `test_list]` `# print result``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

 `# Python3 code to demonstrate``# Records element list Maximum``# using map() + lambda + max()` `# initializing list``test_list ``=` `[(``'key1'``, [``3``, ``4``, ``5``]), (``'key2'``, [``1``, ``4``, ``2``]), (``'key3'``, [``9``, ``3``])]` `# printing original list``print``(``"The original list : "` `+` `str``(test_list))` `# using map() + lambda + max()``# Records element list Maximum``res ``=` `list``(``map``(``lambda` `x: (x[``0``], ``max``(x[``1``])), test_list))` `# print result``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

 `# Python3 code to demonstrate``# Records element list Maximum` `# initializing list``test_list ``=` `[(``'key1'``, [``3``, ``4``, ``5``]), (``'key2'``, [``1``, ``4``, ``2``]), (``'key3'``, [``9``, ``3``])]` `# printing original list``print``(``"The original list : "` `+` `str``(test_list))` `# Records element list Maximum``res ``=` `[]` `# Iterating over list``for` `i ``in` `test_list:` `    ``b ``=` `i[``1``]` `    ``# Sorting list elements``    ``b.sort()` `    ``res.append((i[``0``], b[``-``1``]))` `# Printing result``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:

1. Initialize an empty list to store the result.
2. Iterate over the input list test_list using a for loop.
3. For each tuple in the list, extract the key and list values.
4. Find the maximum value in the list using the max() function.
5. Create a new tuple with the key and maximum value.
6. Append this tuple to the result list.
7. Return the result list.

Below is the implementation of the above approach:

## Python3

 `# Python3 code to demonstrate``# Records element list Maximum``# using for loop` `# initializing list``test_list ``=` `[(``'key1'``, [``3``, ``4``, ``5``]), (``'key2'``, [``1``, ``4``, ``2``]), (``'key3'``, [``9``, ``3``])]` `# printing original list``print``(``"The original list : "` `+` `str``(test_list))` `# using for loop``# Records element list Maximum``res ``=` `[]` `for` `key, lst ``in` `test_list:``    ``max_val ``=` `max``(lst)``    ``res.append((key, max_val))` `# print result``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

 `# Python3 code to demonstrate``# Records element list Maximum``# using map() and max()` `# initializing list``test_list ``=` `[(``'key1'``, [``3``, ``4``, ``5``]), (``'key2'``, [``1``, ``4``, ``2``]), (``'key3'``, [``9``, ``3``])]` `# printing original list``print``(``"The original list : "` `+` `str``(test_list))` `# using map() and max()``# Records element list Maximum``res ``=` `list``(``map``(``lambda` `x: (x[``0``], ``max``(x[``1``])), test_list))` `# Printing the result``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``original_list ``=` `[(``'key1'``, [``3``, ``4``, ``5``]), (``'key2'``, [``1``, ``4``, ``2``]), (``'key3'``, [``9``, ``3``])]` `# Sorting the list based on the last value of each tuple in descending order``sorted_list ``=` `merge_sort(original_list, key``=``lambda` `x: x[``1``][``-``1``], reverse``=``True``)` `# Extracting maximum value from each tuple in the sorted list``max_values_list ``=` `[(t[``0``], ``max``(t[``1``])) ``for` `t ``in` `sorted_list]` `# Printing output``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).

Previous
Next