Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing 1 required positional argument - Why?

Tags:

python

I have written this code:

keyList=['a','c','b','y','z','x']
letterlist=['b','c','a','z','y','x']

def keyL(x, y):
    xIndex=keyList.index(x)
    yIndex=keyList.index(y)
    print(cmp(xIndex,yIndex))
    return cmp(xIndex,yIndex)



print(letterlist)


letterlist.sort(key=lambda x, y: keyL(x, y))
print(letterlist)

But when I run the code, I have this error:

File "C:\Python33\prova.py", line 14, in <module>
    letterlist.sort(key=lambda x, y: keyL(x, y))
TypeError: <lambda>() missing 1 required positional argument: 'y'

Why? I have written all the arguments of lambda...

like image 344
hteo Avatar asked Dec 17 '13 18:12

hteo


1 Answers

The sort key function is only ever passed one argument, yet your lambda wants to have 2 arguments. The key function used for list.sort() or sorted() is not a cmp() function.

Just use keyList.index() as your key function here:

letterlist.sort(key=keyList.index)

Python then sorts the list based on the values returned by the key function. Under the hood Python will 'decorate' your values with the key function, sort the values, then undecorate again.

If you do have a complex cmp() function and you don't quite know how to translate it to a key function, you can use the functools.cmp_to_key() utility function to wrap the cmp() function for you:

from functools import cmp_to_key

letterlist.sort(key=cmp_to_key(keyL))

but do note that the built-in cmp() function has been removed from Python 3 altogether.

like image 63
Martijn Pieters Avatar answered Sep 21 '22 20:09

Martijn Pieters