Reputation: 1267
Suppose I have a list of dates in the string format, 'YYYYMMDD.' How do I sort the list in regular and reverse order?
Upvotes: 1
Views: 574
Reputation: 40884
Strings sort naturally. Use list.sort
(in-place) or built-in sorted
(copying).
Both accept a boolean parameter named reverse
which defaults to False
; set to True
fr reverse order.
Upvotes: 3
Reputation: 375494
These are the two ways:
print sorted(my_list)
print sorted(my_list, reverse=True)
The whole reason people use dates in YYYYMMDD format is so that lexicographic (string) sorting will accomplish a date sort.
Upvotes: 7
Reputation: 304137
For that particular format, you can just sort them as strings
>>> sorted(['20100405','20121209','19990606'])
['19990606', '20100405', '20121209']
>>> sorted(['20100405','20121209','19990606'], reverse=True)
['20121209', '20100405', '19990606']
This works because in that format the digits are in the order of most significant to least significant
Upvotes: 11