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?
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?
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.
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))]
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.