How is the lambda function working here with any parentheses?

import codecademylib
import pandas as pd

df = pd.read_csv('employees.csv')

get_last_name = lambda x: x.split()[-1]

df["last_name"] = df.name.apply(get_last_name)

print(df)

Here when I call the get_last_name lambda function on df.name how come is the code working flawlessly even though I have not given any parentheses after calling get_last_name on df.name.apply. Can anyone explain? Or do I simply assume “.apply” is taking care of things here for me?

There would be no meaningful way to call your function without having any input for it. So since you are not handling any appropriate input for your function then you better not be calling it either.
Also keep in mind that lambda doesn’t do anything special, I’d prefer a def-statement for defining that function. A big part of the reason why you would use a lambda expression is if you’re not going to name it, but you are naming it anyway by assigning a variable to it. The lambda would make more sense if it was written directly in the argument list to df.name.apply. A lambda expression is sometimes also referred to as an “anonymous function” precisely because it isn’t given a name.

2 Likes