On 29/03/2015 16:25, boB Stepp wrote:
On Sun, Mar 29, 2015 at 2:53 AM, Alan Gauld <[email protected]> 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!
The practice of returning None is standard in Python for anything that
works in place, so as a parallel see also the difference between
reverse() and reversed()
As for saving a line of code, I'd much rather write three or four lines
that I can understand at a glance in six months time [or even tomorrow
:) ] rather than a potentially obtuse one liner.
<groan>
Glad you've got this sorted
</groan>
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor