How to sort with lambda in Python

Niklas R. picture Niklas R. · Sep 22, 2010 · Viewed 242.4k times · Source

In Python, I am trying to sort by date with lambda. I can't understand my error message. The message is:

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

The line I have is

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

Answer

kennytm picture kennytm · Sep 22, 2010

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.