Search code examples
pythonsortingfunctional-programminganonymous-function

How to sort with lambda in Python


I am trying to sort some values by attribute, like so:

a = sorted(a, lambda x: x.modified, reverse=True)

I get this error message:

<lambda>() takes exactly 1 argument (2 given)

Why? How do I fix it?


This question was originally written for Python 2.x. In 3.x, the error message will be different: TypeError: sorted expected 1 argument, got 2.


Solution

  • Use

    a = sorted(a, key=lambda x: x.modified, reverse=True)
    #             ^^^^
    

    On Python 2.x, the sorted function takes its arguments in this order:

    sorted(iterable, cmp=None, key=None, reverse=False)
    

    so without the key=, the function you pass in will be considered a cmp function which takes 2 arguments.