[Python-ideas] suggestion about the sort() function of the list instance

Jonathan Goble jcgoble3 at gmail.com
Sun Feb 26 22:37:24 EST 2017


On Sun, Feb 26, 2017 at 10:23 PM qhlonline <qhlonline at 163.com> wrot

> Hi, all
>     I have a suggestion that, the sort() member method of the list
> instance, should return the 'self' as  the result of list.sort() call.
>     Now list.sort() returns nothing, so that I can NOT write code like
> this:
>
>     res =  {item: func(item) for item in item_list.sort()}
>
>     It feels bad.
>
> Regards!
>

list.sort() does not return anything on purpose, to remind you that it
operates by side effect (i.e. that calling list.sort() mutates the list
in-place). If you want it to return the list, use sorted() to get a copy of
the list.

Also, for your specific example, I wouldn't use a comprehension in the
first place. I'd probably do something like this:

item_list.sort()
res = dict(zip(item_list, map(func, item_list)))

But sorting the item_list is pointless in this case, since dictionaries are
unordered [1], so the sorting has no real effect in this case, other than
the fact that the list is now sorted for the benefit of subsequent code, if
that should be relevant.

[1] Dictionaries are ordered in CPython 3.6, but this behavior cannot be
relied upon, as doing so means your code won't work on older versions of
CPython, nor is it guaranteed to work in other implementations of Python
3.6.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170227/1d2c9135/attachment.html>


More information about the Python-ideas mailing list