Search code examples
pythonpython-2.7

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?


Solution

  • 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.