How work sort()

I want to sort the list of numbers by ascending order.
But my code returns None instead of [3, 2, 1]:

print([1, 2, 3].sort())

Please explain to me how sort() works

help([1,2,3].sort)

will show you that it sorts the list inplace and returns None.
If you want a new sorted list, you should use sorted

sorted([1, 2, 3])
1 Like

I have a similar problem:

a = ["A", "B"]
print(a.remove("A"))

It returns None.
How can I fix it?

Here too, remove modifies the list but does not return it (precisely for that reason IIRC).
you could print the modified list after the removing:

a.remove("A")
print(a)
1 Like

For some additional context: in Python there is a convention that if
something makes a new object it returns the object, as otherwise nobody
would get to use it. But if something modifies an object, it generally
returns None.

So list.sort rearranges the items in the list in place, and returned
None.

The sorted function makes a new list containing the elements of the
old list sorts, and therefore returns the new list.

You will find this pattern pretty commonly.

1 Like

Or more precisely: It generally does NOT return the original object. For example, list.pop returns the item popped off the list, leaving the list one item shorter.

2 Likes

As it happens, I have written about this topic already in general terms.

Please see:

1 Like