Hi in this article let's look into starting a list containing a list of tuples based on the last element of the tuple. Given a list of tuples you have to sort the items in an ascending order as per the last item of a tuple.
For example in the below list of tuples we have 100, 50, 90, and 10 as the last items of a tuple.
List = [(1, 2, 3, 100), (4, 5, 50), (6, 90), (7, 8, 9, 10)]
If we try to sort the above list based on the last element of tuple, we get the last items of tuple as 10, 50, 90 and 100 as shown below.
List = [(7, 8, 9, 10), (4, 5, 50), (6, 90), (1, 2, 3, 100)]
Let's try to solve this using a Python program.
Python supports sort inbuilt function The shortest iterable object based on key, in the above program iterable object is list of tuples and key is last item of a tuple. Let's use the inbuilt sort function to sort the list of tuples in ascending order and print them.
We also need to write a function that returns the last item of a tuple; this function is given as the key to the sort.
def return_last_element(tuple_item):
return tuple_item[-1]
Get a new list of tuples and pass the list to the sort function, get the return value stored in the new list, and print the final list
my_list = [(1, 3, 4), (0, 1, -1), (900, 89, -900), (1, 2, 3, 4), (-1000,)]
final_list = sorted(my_list, key=return_last_element)
print(final_list)
OUTPUT 1:
[(-1000,), (900, 89, -900), (0, 1, -1), (1, 3, 4), (1, 2, 3, 4)]
Final program with different input list
def return_last_element(tuple_item):
return tuple_item[-1]
my_list = [(1, 2, 3, 100), (4, 5, 50), (6, 90), (7, 8, 9, 10)]
sorted_list = sorted(my_list, key=return_last_element)
print(sorted_list)
OUTPUT 2:
[(7, 8, 9, 10), (4, 5, 50), (6, 90), (1, 2, 3, 100)]
Conclusion: let me know if any queries / suggestions by commenting down below.
Keywords: Write a Python Program to Get a List Sorted in Increasing Order by The Last Element in Each Tuple From a Given List of Non Empty Tuples
0 Comments