Rajeev
Rajeev

Reputation: 46909

Python list sort in descending order

How can I sort this list in descending order?

timestamps = [
    "2010-04-20 10:07:30",
    "2010-04-20 10:07:38",
    "2010-04-20 10:07:52",
    "2010-04-20 10:08:22",
    "2010-04-20 10:08:22",
    "2010-04-20 10:09:46",
    "2010-04-20 10:10:37",
    "2010-04-20 10:10:58",
    "2010-04-20 10:11:50",
    "2010-04-20 10:12:13",
    "2010-04-20 10:12:13",
    "2010-04-20 10:25:38"
]

Upvotes: 481

Views: 899175

Answers (7)

cottontail
cottontail

Reputation: 23021

Especially if the data is numeric, negation can be used to sort in descending order. This is especially useful if you need to pass a sorting key anyway. For example, if the data was as follows:

data = ['9', '10', '3', '4.5']
sorted(data, reverse=True)                      # doesn't sort correctly
sorted(data, key=lambda x: -float(x))           # sorts correctly
#                          ^ negate here

# that said, passing a key along with reverse=True also work
sorted(data, key=float, reverse=True)           # ['10', '9', '4.5', '3']

For an example with datetime, that would look like as follows:

from datetime import datetime
ts = ["04/20/2010 10:07:30", "12/01/2009 10:07:52", "01/13/2020 10:08:22", "12/01/2009 12:07:52"]
ts.sort(key=lambda x: -datetime.strptime(x, '%m/%d/%Y %H:%M:%S').timestamp())
#                                                               ^^^^ convert to a number here
ts
# ['01/13/2020 10:08:22', '04/20/2010 10:07:30', '12/01/2009 12:07:52', '12/01/2009 10:07:52']

Upvotes: 4

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

This will give you a sorted version of the array.

sorted(timestamps, reverse=True)

If you want to sort in-place:

timestamps.sort(reverse=True)

Check the docs at Sorting HOW TO

Upvotes: 591

hamdan
hamdan

Reputation: 313

Here is another way


timestamps.sort()
timestamps.reverse()
print(timestamps)

Upvotes: 6

Russell Dias
Russell Dias

Reputation: 73282

Since your list is already in ascending order, we can simply reverse the list.

>>> timestamps.reverse()
>>> timestamps
['2010-04-20 10:25:38', 
'2010-04-20 10:12:13', 
'2010-04-20 10:12:13', 
'2010-04-20 10:11:50', 
'2010-04-20 10:10:58', 
'2010-04-20 10:10:37', 
'2010-04-20 10:09:46', 
'2010-04-20 10:08:22',
'2010-04-20 10:08:22', 
'2010-04-20 10:07:52', 
'2010-04-20 10:07:38', 
'2010-04-20 10:07:30']

Upvotes: 11

mostafa elmadany
mostafa elmadany

Reputation: 159

you simple type:

timestamps.sort()
timestamps=timestamps[::-1]

Upvotes: 14

Wolph
Wolph

Reputation: 80011

You can simply do this:

timestamps.sort(reverse=True)

Upvotes: 67

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798486

In one line, using a lambda:

timestamps.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True)

Passing a function to list.sort:

def foo(x):
    return time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6]

timestamps.sort(key=foo, reverse=True)

Upvotes: 429

Related Questions