October 13, 2024

Python Sorted with Reverse Option

The sorted() function in Python is used to return a new sorted list from the elements of any iterable. It offers a versatile way to sort data, with an optional reverse parameter that allows you to sort in descending order.

1. Basic Usage of sorted()

The sorted() function can be used to sort a list in ascending order by default:

numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 2, 5, 5, 6, 9]

2. Sorting in Descending Order with reverse=True

To sort the list in descending order, use the reverse=True argument:

numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)  # Output: [9, 6, 5, 5, 2, 1]

3. Sorting with Custom Key Functions

You can also use the key parameter to sort elements based on a custom function:

words = ['banana', 'apple', 'cherry']
sorted_words = sorted(words, key=len)
print(sorted_words)  # Output: ['apple', 'banana', 'cherry']

# Descending order with custom key
sorted_words_desc = sorted(words, key=len, reverse=True)
print(sorted_words_desc)  # Output: ['banana', 'cherry', 'apple']

4. Example: Sorting a List of Tuples

Sorting a list of tuples based on a specific element within each tuple:

tuples = [(1, 'apple'), (3, 'banana'), (2, 'cherry')]
sorted_tuples = sorted(tuples, key=lambda x: x[1])
print(sorted_tuples)  # Output: [(1, 'apple'), (3, 'banana'), (2, 'cherry')]

# Descending order
sorted_tuples_desc = sorted(tuples, key=lambda x: x[1], reverse=True)
print(sorted_tuples_desc)  # Output: [(2, 'cherry'), (3, 'banana'), (1, 'apple')]

5. Summary

The sorted() function is a powerful tool for sorting lists in Python. By using the reverse=True parameter, you can easily sort lists in descending order. Additionally, the key parameter allows for more complex sorting based on custom criteria.