13

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?

1
  • sorted is a built-in function that order your str element with an alphabetical algorithm, rather than just for reverse your sequence. Use help(sorted) in your kernal to see the details.
    – Feishi
    Apr 16, 2017 at 1:04

5 Answers 5

21

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.

10

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)
1
  • But this is pointless effort because you do not need to sort, because the sort is already established, you only need to reverse. If you want to reverse, stay away from sort. If you want to sort, by all means... but that's not what this question needs.
    – NeilG
    Mar 21 at 8:21
5

If you want to do an in-place reverse sort, you can also do this:

a.sort(reverse=True)
4

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.

1

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) 
1
  • Did you even read the question? Did you even read your own answer? Did you compare the result to what's required? You've made the same mistake as the OP. 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.
    – NeilG
    Mar 21 at 8:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.