Print a sorted list


Why executing the following:




while executing the following:

a = [7,1,0]


[0, 1, 7]


Asked By: pebox11



Because .sort() operates on the list and returns None, while print(sorted(a)) prints what you want but does not alter the list

Answered By: GPhilo

sort() sorts the list but returns None. You probably want sorted.


Answered By: 0x5453

The .sort() method sorts the list in place and returns None. The list becomes sorted, which is why printing the list displays the expected value. However, print(x.sort()) prints the result of sort(), and sort() returns None.

Answered By: Bryan Oakley

Because in the first example print([7,1,0].sort()) you are printing value returned by sort() and sort() does not return anything.
While later you are performing sort() on the list a and then printing the lista.

Sort() changes order of elements in the list a and does not return anything.

Use sorted() to get sorted list as returned value.

Answered By: Talita
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.