While using some built-in functions like sorted, sum... I noticed the usage of key=lambda
What is lambda? How does it work?
What other functions use key=lambda?
Are there any other key values like, key=?
Use key when you want to sort the data using the Python lambda function. The key lambda sorted could treat string items as an int to achieve this. This is why the key keyword argument is used.
To define lambda, you specify the object property you want to sort and python's built-in sorted function will automatically take care of it. If you want to sort by multiple properties then assign key = lambda x: (property1, property2). To specify order-by, pass reverse= true as the third argument(Optional. A Boolean.
Lambda functions are used when you need a function for a short period of time. This is commonly used when you want to pass a function as an argument to higher-order functions, that is, functions that take other functions as their arguments.
A lambda
is an anonymous function:
>>> f = lambda: 'foo' >>> print f() foo
It is often used in functions such as sorted()
that take a callable as a parameter (often the key
keyword parameter). You could provide an existing function instead of a lambda
there too, as long as it is a callable object.
Take the sorted()
function as an example. It'll return the given iterable in sorted order:
>>> sorted(['Some', 'words', 'sort', 'differently']) ['Some', 'differently', 'sort', 'words']
but that sorts uppercased words before words that are lowercased. Using the key
keyword you can change each entry so it'll be sorted differently. We could lowercase all the words before sorting, for example:
>>> def lowercased(word): return word.lower() ... >>> lowercased('Some') 'some' >>> sorted(['Some', 'words', 'sort', 'differently'], key=lowercased) ['differently', 'Some', 'sort', 'words']
We had to create a separate function for that, we could not inline the def lowercased()
line into the sorted()
expression:
>>> sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower()) File "<stdin>", line 1 sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower()) ^ SyntaxError: invalid syntax
A lambda
on the other hand, can be specified directly, inline in the sorted()
expression:
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower()) ['differently', 'Some', 'sort', 'words']
Lambdas are limited to one expression only, the result of which is the return value.
There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.
In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions.
Basically it is used for defining anonymous functions that can/can't take argument(s) and returns value of data/expression. Let's see an example.
>>> # Defining a lambda function that takes 2 parameters(as integer) and returns their sum ... >>> lambda num1, num2: num1 + num2 <function <lambda> at 0x1004b5de8> >>> >>> # Let's store the returned value in variable & call it(1st way to call) ... >>> addition = lambda num1, num2: num1 + num2 >>> addition(62, 5) 67 >>> addition(1700, 29) 1729 >>> >>> # Let's call it in other way(2nd way to call, one line call ) ... >>> (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 me give an answer of your 2nd question. The 1st answer is also great. This is my own way to explain with another example.
Suppose we have a list of items(integers and strings with numeric contents) as follows,
nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
and I want to sort it using sorted() function, lets see what happens.
>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"] >>> sorted(nums) [1, 3, 4, '-1', '-10', '2', '5', '8'] >>>
It didn't give me what I expected as I wanted like below,
['-10', '-1', 1, '2', 3, 4, '5', '8']
It means we need some strategy(so that sorted could treat our string items as an ints) to achieve this. This is why the key keyword argument is used. Please look at the below one.
>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"] >>> sorted(nums, key=int) ['-10', '-1', 1, '2', 3, 4, '5', '8'] >>>
Lets use lambda function as a value of key
>>> names = ["Rishikesh", "aman", "Ajay", "Hemkesh", "sandeep", "Darshan", "Virendra", "Shwetabh"] >>> names2 = sorted(names) >>> names2 ['Ajay', 'Darshan', 'Hemkesh', 'Rishikesh', 'Shwetabh', 'Virendra', 'aman', 'sandeep'] >>> # But I don't want this o/p(here our intention is to treat 'a' same as 'A') ... >>> names3 = sorted(names, key=lambda name:name.lower()) >>> names3 ['Ajay', 'aman', 'Darshan', 'Hemkesh', 'Rishikesh', 'sandeep', 'Shwetabh', 'Virendra'] >>>
You can define your own function(callable) and provide it as value of key.
Dear programers, I have written the below code for you, just try to understand it and comment your explanation. I would be glad to see your explanation(it's simple).
>>> def validator(item): ... try: ... return int(item) ... except: ... return 0 ... >>> sorted(['gurmit', "0", 5, 2, 1, "front", -2, "great"], key=validator) [-2, 'gurmit', '0', 'front', 'great', 1, 2, 5] >>>
I hope it would be useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With