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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With