0

I have an array which contains some elements.

How by doing arr[::-1] sort the entire array?

What is the logic behind that?

martineau
  • 119,623
  • 25
  • 170
  • 301
amitabes
  • 117
  • 1
  • 3
  • 3
    `arr[::-1]` does not sort a list, it only reverses a list. – Vedang Mehta Aug 16 '16 at 12:03
  • Sorting the array would change the order of all its elements such that `arr[i] <= arr[i+1]`. `arr[::-1]` doesn't do that, it just reverses the order in which they occur in the array. – martineau Aug 16 '16 at 13:09

1 Answers1

5

This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string. Example:

>>> 'hello world'[::-1]
'dlrow olleh'

See also

Community
  • 1
  • 1
Shaig Khaligli
  • 4,955
  • 5
  • 22
  • 32