In Python, lambda
is a keyword used to define anonymous functions(i.e., functions that don't have a name), sometimes called lambda functions (after the keyword, which in turn comes from theory).
Let's see some examples:
>>> # Define a lambda function that takes 2 parameters and sums them:
>>> lambda num1, num2: num1 + num2
<function <lambda> at 0x1004b5de8>
>>>
>>> # We can store the returned value in variable & call it:
>>> addition = lambda num1, num2: num1 + num2
>>> addition(62, 5)
67
>>> addition(1700, 29)
1729
>>>
>>> # Since it's an expression, we can use it in-line instead:
>>> (lambda num1, num2: num1 + num2)(120, 1)
121
>>> (lambda num1, num2: num1 + num2)(-68, 2)
-66
>>> (lambda num1, num2: num1 + num2)(-68, 2**3)
-60
>>>
Now let's see how this works in the context of sorted
.
Suppose we have a list like so, with a mixture of integers and strings with numeric contents:
nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
and that we would like to sort the values according to the number they represent: thus, the result should be ['-10', '-1', 1, '2', 3, 4, '5', '8']
.
If we try to sort it using sorted
, we get the wrong result:
>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums) # in 2.x
[1, 3, 4, '-1', '-10', '2', '5', '8']
>>> # In 3.x, an exception is raised instead
By using a key
for sorted
, however, we can sort the values according to the result of applying the key
function to each value:
>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums, key=int)
['-10', '-1', 1, '2', 3, 4, '5', '8']
>>>
Since lambda
creates a callable (specifically, a function), we can use one for the key
:
>>> names = ["Rishikesh", "aman", "Ajay", "Hemkesh", "sandeep", "Darshan", "Virendra", "Shwetabh"]
>>> names2 = sorted(names)
>>> names2
['Ajay', 'Darshan', 'Hemkesh', 'Rishikesh', 'Shwetabh', 'Virendra', 'aman', 'sandeep']
>>> # Let's use a lambda to get a case-insensitive sort:
>>> names3 = sorted(names, key=lambda name:name.lower())
>>> names3
['Ajay', 'aman', 'Darshan', 'Hemkesh', 'Rishikesh', 'sandeep', 'Shwetabh', 'Virendra']
>>>
key
in this case is a keyword argument and has nothing to do withlambda
. – Acre