Reputation: 8165
This code snippet:
a = [3, 2, 1]
a.sort()
produces [1, 2, 3]
list. Why
[3, 2, 1].sort()
doesn't produce the same result? Is there a "one-liner" to accomplish this?
Upvotes: 2
Views: 94
Reputation: 250961
>>> [3, 2, 1].sort()
It does sort this list object but as the number of references(variables pointing) to this list are 0, so it is garbage collected.(i.e we can't access this list anymore)
Coming to your first question, list.sort()
sorts a list in-place and returns None
.
>>> a = [3, 2, 1]
>>> a.sort()
>>> a
[1, 2, 3]
If you want a
to stay as it is, use sorted
and assign the result back to some variable.
>>> a = [3, 2, 1]
>>> b = sorted(a)
>>> b
[1, 2, 3]
>>> a
[3, 2, 1]
Upvotes: 2
Reputation: 133564
list.sort
is a method that sorts an existing list therefore returning None
sorted
is a builtin function that creates a new sorted list from its input and returns it.
Upvotes: 1