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)
reverse
, stay away from sort
. If you want to sort
, by all means... but that's not what this question needs.
If you want to do an in-place reverse sort, you can also do this:
a.sort(reverse=True)
You can also reverse in place:
>>> a = ['L', 'N', 'D']
>>> a.reverse()
>>> a
['D', 'N', 'L']
But please note it changes the list, doesn't create (return) a new one.
You had it almost right the first time. Try this:
#This will sort the list temporarily into reverse alphabetical order.
print(sorted(a, reverse=True)
#This will sort the list temporarily into reverse order.
print(sorted(a, reverse=False)
reversed
is needed, not sorted
. There is no sorting required. Three months later you come along and provide an additional wrong answer to an already answered question of the simplest possible order. Please delete this answer, for the sake of the poor noobs who read this answer and may actually try to understand what you've written.
sorted
is a built-in function that order yourstr
element with an alphabetical algorithm, rather than just for reverse your sequence. Usehelp(sorted)
in your kernal to see the details.