Sort Short_Names in Reverse Alphabetic Order

I dont understand what I am doing wrong:

Sort short_names in reverse alphabetic order. Sample output from given program:

['Tod', 'Sam', 'Joe', 'Jan', 'Ann']

My code:

short_names = ['Jan', 'Sam', 'Ann', 'Joe', 'Tod']

short_names.sort()

print(short_names)
1

3 Answers

sort function has a reverse option:

short_names.sort(reverse=True)

As always, first have a look at the documentation for list.sort:

sort(*, key=None, reverse=None)

This method sorts the list in place, using only < comparisons between items.

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

So the items in your list will be sorted from "smallest" to "largest" using the < comparion, which for strings means lexicographical ordering (A < AB < B). To sort it in reverse order, use the reverse parameter:

short_names.sort(reverse=True)

For more information have a look at the official Sorting HOW TO.

short_names.sort()
short_names.reverse()
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest