Explain Codes LogoExplain Codes Logo

Python list sort in descending order

python
functions
dataframe
pandas
Nikita BarsukovbyNikita Barsukov·Dec 10, 2024
TLDR

Time is of the essence, so here's the meat and potatoes. Sort a Python list in descending order using the sort() method with the reverse=True parameter for in-place sorting, or the sorted() function to obtain a sorted copy:

my_list.sort(reverse=True) # In-place sorted_copy = sorted(my_list, reverse=True) # New list, original remains untouched

From my_list = [3, 1, 4, 1, 5, 9, 2], both methods yield [9, 5, 4, 3, 2, 1, 1]. Pick your poison based on whether you want to keep the original order intact.

Descending sort with timestamps

When you have a list of timestamps, remember to first convert them into datetime objects for efficient sorting. Here's a slice of how to do it:

from datetime import datetime timestamps = ["2020-01-02 04:05:06", "2020-01-03 07:08:09", "2020-01-01 01:02:03"] # Gotta convert 'em all datetime_objects = [datetime.strptime(ts, '%Y-%m-%d %H:%M:%S') for ts in timestamps] # Sort in descending order, like a boss datetime_objects.sort(reverse=True)

Always check to make sure the latest timestamp is leading the pack after sorting!

Customizing your sort with lambda

Want to be unique? Use a lambda function as the key parameter in sorted() or sort(), and dictate your own custom sorting logic:

my_list = [('apples', 2), ('bananas', 3), ('carrots', 1)] # Sort by quantity in descending order, because who needs alphabets? my_list.sort(key=lambda item: item[1], reverse=True)

Remember, lambda doesn't mean it's related to calculus. It's just Python's way of saying "anonymous function"!

Using reverse() for fun and profit

Got a list already sorted in ascending order, and need it the other way round? No sweat! reverse() is here to save the day:

ascending_list = [1, 2, 3, 4, 5] ascending_list.reverse() # Abracadabra!

Alternatively, you can also slice to reverse: descending_list = ascending_list[::-1]. Who knew Python also did magic tricks?

Advanced techniques

Handling puzzles aka nested structures

Efficiently handling lists with nested structures like dictionaries is key. Use the key parameter to extract a comparison key from your sorting puzzle:

# Sorting dictionaries by a value data = [{"name": "Alice", "score": 10}, {"name": "Bob", "score": 8}] sorted_data = sorted(data, key=lambda x: x['score'], reverse=True) # Score! Alice wins

Stable sorting: keeping order in chaos

Python's sort is stable. This means that if two elements have the same key, their original order remains the same. Harness the power of stability when performing multiple sorting passes for complex lists:

# Sort by score, then by name data.sort(key=lambda x: x['name']) # First, let's arrange by name data.sort(key=lambda x: x['score'], reverse=True) # Then by score. Ties? Original name order is kept. No penalty shootout required!

Memory-efficient sorting, because who likes wastage?

When memory is precious and limited, use sort(). As an in-place method, it consumes less memory than sorted(), which creates a new list:

large_list.sort(reverse=True) # In-place sorting. No additional memory needed. Isn't that just sweet?