0

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)
Simon H
  • 2,495
  • 4
  • 30
  • 38
trio
  • 19
  • 1
  • 1
  • 1
  • 3
    Possible duplicate of [Python list sort in descending order](https://stackoverflow.com/questions/4183506/python-list-sort-in-descending-order) – Sriram Sitharaman Jul 12 '17 at 06:19

5 Answers5

1

sort function has a reverse option:

short_names.sort(reverse=True)
Błotosmętek
  • 12,717
  • 19
  • 29
0

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.

Community
  • 1
  • 1
Christian König
  • 3,437
  • 16
  • 28
0
short_names.sort()
short_names.reverse()
cigien
  • 57,834
  • 11
  • 73
  • 112
0

This worked for me!

user_input = input()
short_names = user_input.split()

short_names.sort()
short_names.reverse()

print(short_names)
Rajat Jaiswal
  • 645
  • 4
  • 15
JRO
  • 1
-2

I'm doing this lab right now, and this is what your code should look like for the zybook, based on the methods we have learned.

user_input = input()
short_names = user_input.split()
short_names.sort()
short_names.reverse()
print(short_names)
Skandix
  • 1,916
  • 6
  • 27
  • 36
Maud_c7
  • 1
  • 1