Today, I encounter a code slide below and I am confused that why key=takeSecond
is a valid syntax. I mean, shouldn't it be key=takeSecond(elem)
? However, the code works perfectly and I don't know why.
# take second element for sort
def takeSecond(elem):
return elem[1]
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
random.sort(key=takeSecond)
# print list
print('Sorted list:', random)