When it is required to convert the rear column of a multi-sized matrix, a simple iteration and the ‘append’ method along with negative indexing is used.
Example
Below is a demonstration of the same −
my_list = [[41, 65, 25], [45, 89], [12, 65, 75, 36, 58], [49, 12, 36, 98],[47, 69, 78]] print("The list is : " ) print(my_list) print("The list after sorting is : " ) my_list.sort() print(my_list) my_result = [] for sub_list in my_list: my_result.append(sub_list[-1]) print("The resultant list is : ") print(my_result) print("The list after sorting is : " ) my_result.sort() print(my_result)
Output
The list is : [[41, 65, 25], [45, 89], [12, 65, 75, 36, 58], [49, 12, 36, 98], [47, 69, 78]] The list after sorting is : [[12, 65, 75, 36, 58], [41, 65, 25], [45, 89], [47, 69, 78], [49, 12, 36, 98]] The resultant list is : [58, 25, 89, 78, 98] The list after sorting is : [25, 58, 78, 89, 98]
Explanation
A list of list is defined and is displayed on the console.
It is sorted using the ‘sort’ method.
An empty list is created.
The list is iterated over and the last element (using negative indexing) is accessed.
This is appended to the empty list.
This result is displayed as the output on the console.
This list is again sorted and displayed on the console.