Oddity using sorted with key

Josh English Joshua.R.English at gmail.com
Tue Mar 11 17:13:17 CET 2014

I am running into a strange behavior using the sorted function in Python 2.7. The key parameter is not behaving as the docs say it does:

Here is a snippet of code, simplified from my full program:

#begin code
class Thing(object):
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return "Thing %s" % self.name

stuff = [Thing('a'), Thing('C'), Thing('b'), Thing('2')]
more_stuff = [Thing('d'), Thing('f')]

all_the_stuff = stuff + more_stuff

print list(sorted(all_the_stuff, key=lambda x: x.name.lower))
print list(sorted(all_the_stuff, key=lambda x: x.name.lower()))


The output is:

[Thing d, Thing f, Thing 2, Thing a, Thing b, Thing C]
[Thing 2, Thing a, Thing b, Thing C, Thing d, Thing f]

The second call to sorted works as expected. Just using the method doesn't sort properly.

Any ideas why I'm seeing two different results? Especially as the correct form is giving me the wrong results?

Josh English

More information about the Python-list mailing list