w3resource

Python Exercise: Sort a tuple by its float element

Python tuple: Exercise-23 with Solution

Write a Python program to sort a tuple by its float element.

Sample Solution:

Python Code:

# Create a list of tuples 'price', where each tuple represents an item and its price as a string.
price = [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
# Sort the 'price' list based on the price values (the second element in each tuple).
# The 'key' argument specifies a lambda function to convert the price strings to float values.
# Sorting is done in reverse (descending) order using the 'reverse' argument.
sorted_price = sorted(price, key=lambda x: float(x[1]), reverse=True)

# Print the 'sorted_price' list, which contains the items sorted by price in descending order.
print(sorted_price)

Sample Output:

[('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')] 

Flowchart:

Flowchart: Sort a tuple by its float element

Python Code Editor:

Previous: Write a Python program to remove an empty tuple(s) from a list of tuples.
Next: Write a Python program to count the elements in a list until an element is a tuple.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/tuple/python-tuple-exercise-23.php