5
y = [1, 3, 2, 4]
x = y.sort()
print(x)

x is None. How come this sort of syntax works in, for example, Javascript, and not Python?

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
  • 3
    A function needs to return a value in order to use the returned value. Note what the docs for `sort` say. – Carcigenicate Apr 12 '20 at 16:19
  • 1
    Because `list.sort()` does not return the sorted array, that's happening in-place. It's just how python works/ – rdas Apr 12 '20 at 16:20

3 Answers3

6

sort (and reverse) change the list in-place.

If you want, you can use sorted:

x = sorted(y)

This is explained in the section Data Structures in the documentation.

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
2

Here, y.sort() sorts y and can't be assigned to another variable.Here, you could use sorted() like x = sorted(y) or:

x = [i for i in sorted(y)]

Or lets use a beautiful one-liner:

x = [y.pop(y.index(min(y))) for i in range(len(y))]
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
2

Because sort() is an operation that is executed in place (it doesn't need to be re-assigned). It returns None, just like append(), extend(), and other list methods.

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143