Any tips on how to use lambda functions?

I’ve been programming with python for a while now, and have become quite fluent with the help of codecademy. However, some of the python courses and sections (such as the Pandas course) require you to have a solid understanding of lambda functions. I don’t recall seeing anything about lambda functions in any of the other python courses I’ve taken on this site, and was wondering if someone could help explain to me how they work, or point me to a codecademy lesson that does the same.

1 Like

A lambda is an anonymous function. Typically these are callable objects with just a call function. In python they are defined like this

def <lambda>(arguments):
    return expression

and implemented like so

def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

Another use of lambdas

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

You can do things like sort by any field on the fly.
Lambdas essentially give you nice short syntax for a bunch of functionality.
In a language like c++ lambdas can give you functionality resembling duck typing.

Lambdas are NOT essential. It is just a way of accomplishing functionality quickly. It isn’t always the best solution and never the only one. But they can be extremely useful and fun to use.

1 Like

From the python documentation

Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you’re too lazy to define a function.
Functions are already first class objects in Python, and can be declared in a local scope. Therefore the only advantage of using a lambda instead of a locally-defined function is that you don’t need to invent a name for the function – but that’s just a local variable to which the function object (which is exactly the same type of object that a lambda expression yields) is assigned!

If you read on in the docs - they very strongly and humorously suggest you to never use them.
I love lambdas in languages like c++
They aren’t to necessary in python

TL:DR
Don’t be intimidated!

2 Likes