Using sorted() to print a list in reverse alphabetical order

Can anyone help me use sorted() to print a list in reverse alphabetical order please?

Here is my list:

places = [‘Iceland’, ‘Japan’, ‘Manchester’, ‘Norwich’]

As I understand it, the sorted() function can also accept a reverse=True argument to display the list in reverse alpha order, but I am having trouble getting the program to do that

Many thanks in advance

Yes exactly:

In [1]: sorted(places, reverse=True)
Out[1]: ['Norwich', 'Manchester', 'Japan', 'Iceland']

Hi Simon,

If you are having trouble with something, you should show us what you
tried and what result you get. For example:

places = ['Iceland', 'Japan', 'Manchester', 'Norwich']
sorted(places, reversed=True)

gives a traceback:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'reversed' is an invalid keyword argument for sort()

But if I spell it correctly, it works:

sorted(places, reverse=True)
# --> returns ['Norwich', 'Manchester', 'Japan', 'Iceland']

Note that sorted() creates a new list, a copy of the original. If you
want to sort the list in-place without making a copy, use the sort
method like this:


Since your list is already sorted, if you just want to reverse it, you
can do that:


Thanks for replying Steven. This is the code:

places = [‘Belgium’, ‘Iceland’, ‘Norwich’, ‘Ulan Bator’]
sorted(places, reverse=True)

I am expecting the program to return
[‘Ulan Bator’, ‘Norwich’, ‘Iceland’, ‘Belgium’]

Instead it is just printing the original list in the original order:

[‘Belgium’, ‘Iceland’, ‘Norwich’, ‘Ulan Bator’]
[Finished in 1.0s]

sorted returns a new list. You do not save the result of sorted(places, reverse=True) in a variable.

Thanks for replying

Can you see what I’ve done wrong here?

Please don’t post screenshots of code; use Markdown instead.

Both @steven.daprano and I have explained how sorted() works. I suggest you read our replies once more and use that information to figure out the missing pieces :slight_smile:

If you want to sort a list in place, without creating a new list, you
need the sort method:

mylist = [3, 5, 2, 4, 1]
print(mylist)  # --> prints [1, 2, 3, 4, 5]

If you use the sorted function, it makes a copy, which you need to store
in a variable"

mylist = [3, 5, 2, 4, 1]
newlist = sorted(mylist)
print(mylist)  # --> prints the original [3, 5, 2, 4, 1]
print(newlist)  # --> prints [1, 2, 3, 4, 5]