w3resource

Python: Sort a given list of tuples on specified element

Python List: Exercise - 188 with Solution

Write a Python program to sort a given list of tuples on specified element.

Sample Solution:

Python Code:

def sort_on_specific_item(lst, n):
    result = sorted((lst), key=lambda x: x[n])
    return result   
items = [('item2', 10, 10.12), ('item3', 15, 25.10), ('item1', 11, 24.50),('item4', 12, 22.50)]
print("Original list of tuples:")
print(items)
print("\nSort on 1st element of the tuple of the said list:")
n = 0
print(sort_on_specific_item(items, n))
print("\nSort on 2nd element of the tuple of the said list:")
n = 1
print(sort_on_specific_item(items, n))
print("\nSort on 3rd element of the tuple of the said list:")
n = 2
print(sort_on_specific_item(items, n))

Sample Output:

Original list of tuples:
[('item2', 10, 10.12), ('item3', 15, 25.1), ('item1', 11, 24.5), ('item4', 12, 22.5)]

Sort on 1st element of the tuple of the said list:
[('item1', 11, 24.5), ('item2', 10, 10.12), ('item3', 15, 25.1), ('item4', 12, 22.5)]

Sort on 2nd element of the tuple of the said list:
[('item2', 10, 10.12), ('item1', 11, 24.5), ('item4', 12, 22.5), ('item3', 15, 25.1)]

Sort on 3rd element of the tuple of the said list:
[('item2', 10, 10.12), ('item4', 12, 22.5), ('item1', 11, 24.5), ('item3', 15, 25.1)]

Pictorial Presentation:

Python List: Sort a given list of tuples on specified element.

Flowchart:

Flowchart: Sort a given list of tuples on specified element.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to convert a given list of tuples to a list of strings.
Next: Write a Python program to shift last element to first position and first element to last position in a given list.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Big Number Readability:

you can separate zeros with underscore (_)

print(2_000_000)
print(2_000_000 +1)

Output:

2000000
2000001