[Tutor] Why does print(a_list.sort()) return None?
Alan Gauld
alan.gauld at btinternet.com
Sun Mar 29 09:53:30 CEST 2015
On 29/03/15 07:00, Cameron Simpson wrote:
> print(a_list.sort())
>
> is printing the result of "a_list.sort()".
>
> Like most Python functions that operate on something (i.e. .sort, which
> sorts the list in place), the .sort method returns None. And that is
> printed.
But you can use the sorted() function which returns a
sorted copy of the list. So replace your print statement
with
print(sorted(a_list))
gets you the display you want. But does not sort the original.
So it depends on whether you just want to display it, or
actually want to sort it.
Use either:
a_list.sort()
print(a_list)
OR
print(sorted(a_list))
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list