• Register
Welcome to Kodlogs, programming questions and answer website.
0 votes
36 views

Problem :

I am unable to understand what am I missing here:

Sort my_short_names in reverse alphabetic order. The sample output from the given program as below :

['Tody', 'Samy', 'Joey', 'Jany', 'Anny']

Below is my code for your reference :

my_short_names = ['Jany', 'Samy', 'Anny', 'Joey', 'Tody']
my_short_names.sort()
print(my_short_names)

 

by (7.5k points)  

1 Answer

0 votes

Solution  :

I had also faced the similar issue in the recent past. I did lot of research on it and found the solution on it. This is the very common problem with the people getting started.

As I always say, first please have the very careful look at the documentation for list.sort:

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

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

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

So the items in the list will be sorted from the "smallest" to the "largest" using your < comparion operator, which for strings clearly means the lexicographical ordering (A < AB < B). So to start the sort in reverse order, you need to use the reverse parameter as shown below :

my_short_names.sort(reverse=True)

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

 

by (33.3k points)  
...