The Sordid Details: sort() vs. sorted()

I only bring this up because it bit me in the ass a couple of days ago, precipitating a couple of minorly confusing bugfix attempts.

For as long as I can remember, Python has had the sort() function, and it’s always been a function of the list object itself.

>>> mylist = ['monkey', 'horse', 'dog', 'fox', 'iguana']
>>> mylist
['monkey', 'horse', 'dog', 'fox', 'iguana']
>>> mylist.sort()
>>> mylist
['dog', 'fox', 'horse', 'iguana', 'monkey']

Note that calling sort() on the list does not return anything (well, it returns None… samey same). It simply changes the order of the items in the original list object. This can be demonstrated thusly:

>>> mylist = ['monkey', 'horse', 'dog', 'fox', 'iguana']
>>> newlist = mylist.sort()
>>> mylist 
['dog', 'fox', 'horse', 'iguana', 'monkey']
>>> newlist
>>> newlist is None
True

Python 2.4, however, has a built-in function named sorted(). This new function is not a function of the list itself; it is a standard built-in function–like int() or dir()–and you pass the thing to be sorted as the argument to the function itself:

>>> mylist = ['monkey', 'horse', 'dog', 'fox', 'iguana']
>>> newlist = sorted(mylist)
>>> mylist
['monkey', 'horse', 'dog', 'fox', 'iguana']
>>> newlist
['dog', 'fox', 'horse', 'iguana', 'monkey']

And herein lies the ass-biting.

Doing a list.sort() changes the object in-place and returns nothing (None)… but calling sorted(list) leaves the original object unchanged, and returns a newly-created, sorted list object.

Granted, the difference between these is an almost trivial distinction… but if you don’t know ahead of time, you could be left scratching your head for a while.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s