Python list sort in descending order

Question:

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"
]
Asked By: Rajeev

||

Answers:

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

Answered By: Marcelo Cantos

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']
Answered By: Russell Dias

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)

You can simply do this:

timestamps.sort(reverse=True)
Answered By: Wolph

you simple type:

timestamps.sort()
timestamps=timestamps[::-1]
Answered By: mostafa elmadany

Here is another way


timestamps.sort()
timestamps.reverse()
print(timestamps)
Answered By: hamdan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.