Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list in reverse order

I have a list a = ['L', 'N', 'D']. I want to reverse the order of elements in a and get b = ['D', 'N', 'L']. I tried this:

a = ['L', 'N', 'D']
b = sorted(a, reverse=True)

But the output is

b= ['N', 'L', 'D']

Where do I make a mistake?

like image 978
m0_as Avatar asked Apr 16 '17 00:04

m0_as


2 Answers

Your mistake is using sorted, which rearranges the list in order of the elements and ignores where the elements used to be. Instead use

b = a[::-1]

That runs through list a in reverse order. You also could use

b = list(reversed(a))

although the first version is faster.

like image 154
Rory Daulton Avatar answered Sep 22 '22 16:09

Rory Daulton


If you want to use sorted(), you can specify that the index is the key to sort on:

b = sorted(a, key=a.index, reverse=True)
like image 35
bloodrootfc Avatar answered Sep 20 '22 16:09

bloodrootfc