Data Manipulation with Pandas: quiz question 4/6: what is lambda function?


at the end of the Data Manipulation with Pandas course, I was answering the quiz questions but for some of them, the solution implies knowing what a lambda function is, but at this stage this is the very first time I encounter it. Did I miss something??




A lambda function is a small anonymous function.
It can take any number of arguments, but can only have one expression.
The correct syntax is:

lambda arguments : expression

It can be used in many ways, you can either set it to variable and use it as a normal function:

add = lambda a, b : a + b
print(add(1,2)) #prints 3 to the console

you can use it inside any built-in methods, or inside your own functions, for example sorted() and .sort() takes an argument, key which you can pass in a lambda function as argument:

strings = ["a", "c", "b"]
ints = [1,2,3]
tuples = list(zip(strings, ints))
print(tuples.sort()) # prints [("a",1),("b",3),("c",2)]
print(tuples.sort(key=lambda tuple : tuple[1]) # prints [("a",1),("c",2),("b",3)]

Basically the lambda function we passed in as key will get passed an argument into which is the value of a list or any iterable, then our lambda function returns an int (in our case, but it actually returns passedValue[1], the value at index one of the passedValue)
I explained it more in depth in another post/question
But I’d recommend taking a look at a tutorial about lambda
Anyway, if nothing makes sense then just skip the part of the quiz about lambda, because it is advanced python and you’ll probably learn about it later.
I hope this helps :grinning:

1 Like

Thanks a lot!! Now I get what the lambda function is.

I was mainly puzzled by the fact the quiz talked about that without ever having mentioned it in the lesson it came with, nor in any previous lessons I took in the corresponding skill path :slight_smile: Once I understood what that was, I was able to answer the quiz :slight_smile:
Thanks again!

1 Like