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

Steven D'Aprano steve at pearwood.info
Tue Feb 28 19:13:39 EST 2017


On Mon, Feb 27, 2017 at 11:07:33AM +0800, qhlonline wrote:
> 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. 

Having list.sort() and list.reverse() return self is a perfectly good 
design. The advantage is you can write things like this:

list.sort().reverse()

but the disadvantage is that it may fool people into thinking it returns 
a *copy* of the list. Python avoids that trap by returning None, so that 
you cannot write:

sorted_items = items.sort()

but instead people write:

items = items.sort()

so it seems that whatever we do, it will confuse some people.


> Now list.sort() returns nothing, so that I can NOT write 
> code like this:
> 
>     res =  {item: func(item) for item in item_list.sort()}

What is the purpose of the sort? Because dicts are unordered, the 
results will be no different if you just write:

    d = {item: func(item) for item in item_list}


-- 
Steve


More information about the Python-ideas mailing list