Print a sorted list
Question:
Why executing the following:
print([7,1,0].sort())
produces:
None
while executing the following:
a = [7,1,0]
a.sort()
print(a)
produces:
[0, 1, 7]
?
Answers:
Because .sort()
operates on the list and returns None
, while print(sorted(a))
prints what you want but does not alter the list
sort()
sorts the list but returns None
. You probably want sorted
.
print(sorted([7,1,0]))
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
.
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.
Why executing the following:
print([7,1,0].sort())
produces:
None
while executing the following:
a = [7,1,0]
a.sort()
print(a)
produces:
[0, 1, 7]
?
Because .sort()
operates on the list and returns None
, while print(sorted(a))
prints what you want but does not alter the list
sort()
sorts the list but returns None
. You probably want sorted
.
print(sorted([7,1,0]))
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
.
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.