
On Sun, Feb 26, 2017 at 10:23 PM qhlonline <qhlonline@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.