Python Misfeatures

Filed under: python 

Like any language, Python has misfeatures. Some of them are huge (like the distinction between statements and expressions), some are minor unexpected behaviours. This one definitely falls into the latter category. A long-standing wart in Python has been the fact that list.sort() doesn't return a reference to the list. It makes sense that it doesn't because sort() is an in-place sort (for efficiency reasons). However, it's different than most of the other list methods in this respect. I think this makes it a wart. The fact that it's an in-place sort is an implementation detail that I shouldn't need to worry about.

Today I got caught out by something similar to this (although more complicated):

>>> import random
>>> l = range ( 10 )
>>> random.shuffle ( l )
>>> l
[4, 6, 3, 2, 0, 8, 1, 7, 5, 9]
>>> list ( l ).sort ( )
>>> l
[4, 6, 3, 2, 0, 8, 1, 7, 5, 9]
>>>

Looks like sort() didn't do anything, doesn't it? Well something got sorted, it just wasn't what you might expect at first glance. Casting to list() created a new, anonymous list that gots sorted, then immediately discarded.

Now if it was expected behaviour in Python were expected to return a new list (or even a reference to the original list), I'd have probably written

l = list ( l ).sort ( )

and all would have been well.



0 comments Leave a comment