[Tutor] Why does print(a_list.sort()) return None?

boB Stepp robertvstepp at gmail.com
Sun Mar 29 17:25:21 CEST 2015


On Sun, Mar 29, 2015 at 2:53 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> 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))

Thanks for chiming in on this, Alan. I had not noticed that sorted()
was an available option. I had focused on available list methods.
While it does not matter if my actual lists do or do not get sorted,
my intent was to just have a sorted view of the list, so your
suggestion works better here and uses one less line of code. Thanks!


-- 
boB


More information about the Tutor mailing list