Paul Jurczak
Paul Jurczak

Reputation: 8165

Why this Python expression doesn't produce expected result?

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

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

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

rocker_raj
rocker_raj

Reputation: 157

You can use
sorted_array = sorted([2,3,1])

Upvotes: 3

jamylak
jamylak

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

Related Questions