Lesson 11: Python Lambda
- ESTIMATED TIME: 15 mins
- DIFFICULTY: Intermediate
- FUNCTIONS: n/a
- 9 EXERCISES
Lambda, also called the anonymous function, is a perfect way to handle mini function necessities.
It doesn’t require creating definition blocks or naming the function and it all happens in one line.
When you need a proper user defined function defining a proper user function with def
keyword works great.
But sometimes you just need to squeeze your function in another function, or apply it to a column in a data frame or to the elements of an iterable like a list.
The necessity for lambda
arises from those situations where you just need a one time quick solution in a practical way.
Although lambda
syntax can be slightly confusing in the beginning, it can be quite handy once you get a hang of it.
Advantages of lambda is generally it’s tidy, practical and compact and it gets the job done which is a defining a custom function and then using it.
Used Where?
- As a quick alternative to a regular user defined function.
- As an argument for some other functions:
- .sort()
- sorted()
- filter()
- map()
- reduce()
- .apply() : Used with pandas to apply functions to data frames and series.
Syntax do(s)
1) Start your argument with keyword lambda
2) Then variable name followed by colon(:)
3) Last part is the statement
i.e.: lambda x: x+2
Syntax don't(s)
1) You can't have multiple lines of lambda
2) Don't put the colon (:) right after the lambda
statement.
Lambda first, variable second, colon third and statement forth and last.
Function : N/A
This lesson doesn’t introduce a new function.
Example 1: Simple lambda
>>> a = lambda x: x+2
>>> print(a(1))
3
- So, lambda argument starts with
lambda
. It’s the special phrase that starts your process. - Then a variable (usually x for convenience) followed with a colon(:)
- Simply type your statement after the colon(:), and you’re done.
Example 2: print with lambda
>>> a = lambda x: x*3
>>> print(a(33))
99
To simplify things let’s explain again for the fresh programmers:
Program starts with lambda
, then variable name and colon(:), on the right side of the colon simply statement is made regarding what happens to the variable.
Example 3: lambda with logical expression
>>> a = lambda x: x%5==0
>>> print(a(555))
>>> print(a(222))
True
False
We’re using a bunch of different Python operators here. Operators are fundamental to any programming language and Python is no exception.
If you never had a chance to formally study operators, it can be useful to take a look at this Python Operators lesson which has a complete list of Python operators.
Printing the function object
You might at some point encounter a strange output when you’re learning Python. This happens when you try to print function objects directly without without calling it with any value.
What you get will be the id of your function as a memory address rather than any meaningful value to the user.
Example 4: Printing the function
>>> a = lambda x: “Hi”
>>> print(a)
at 0x00000163154BB1E0>
But what is the last printed line that looks weird?
This is because we are trying to print the function itself directly without calling it for any values. What happens is, Python prints the unique memory address of our function. That’s why it looks slightly weird. But it grows on you 🙂
Example 5: To print or not to print
>>> a = lambda x: “Hi”
>>> a(2)
“Hi”
Example 6: lambda with two arguments
>>> a = lambda x, y: x*y
>>> a(11, 6)
66
Tips (optional)
1- One of the most useful aspect of lambda is the ability to pass it as an argument inside some other functions.
We will look at each of these functions in detail in next lessons individually so you don’t have to ponder too much.
But it might be beneficial to take a look at them here to get familiar in advance.
Example 7: .sort() with lambda
.sort()
is a list method that sorts the list’s elements directly.
Also it can take a function as an argument and base its sorting algorithm on this.
Simply pass your lambda
function as an argument inside .sort()
‘s parenthesis.
>>> lst = [1, 5, 66, 7]
>>> lst.sort(key=lambda x: x)
print(lst)
[1, 5, 7, 66]
.sort()
you need to use it with “key=
” keyword.
In this example lambda function is more like a place holder as its statement is the variable itself unchanged. (lambda x: x
)
It basically says, sort based on each element’s value, which is the default tendency of .sort()
function anyway.
But the syntax is nicely demonstrated this way. Example 8: sorted()
with lambda
sorted()
is not a method but a builtin function. It’s main difference from .sort()
method is that it won’t change the original list it will simply output a new list. You have to assign this new list to a variable if you’d like to save it.
>>> lst = [1, 5, 66, 7]
>>> lst_sorted = sorted(lst, key=lambda x: x)
[1, 5, 7, 66]
Again you can see lambda is passed with “key=”.
Another syntactical difference from .sort() is that, since you’re not calling sorted() on a list directly you have to pass the list’s name inside its parenthesis before the “key=” parameter.
Example 9: map()
with lambda
map()
is a useful function that maps all the list items to a desired output. You can also check out our Python map lesson.
For example this example adds +5 to each item in the list.
This time, unlike sorted()
, lambda
comes first inside the parenthesis followed by comma and name of the list.
>>> lst = [1, 5, 66, 7]
>>> lst_mapped = map(lambda x: x+5, lst)
>>> print(list(lst_mapped))
[6, 10, 71, 12]
print()
function when your function already has print in it.
Just call your function and it will do the printing for you. Example 10: filter()
with lambda
Another function that works well with lambda
, filter()
is also similar to the map()
function syntax wise. You can also check out our Python filter lesson.
Inside parenthesis, type your lambda function followed by comma, and then the list you’d like to work on.
The type of functions lambda would implement inside filter
function are usually logical expressions since the list will be filtered based on this logic. Let’s see the example:
>>> lst = [1, 5, 66, 7]
>>> lst_filtered = filter(lambda x: x>5, lst)
>>> print(list(lst_filtered))
[66, 7]
Another point is that you actually don’t have to call your function inside a print() function when your function already has print in it.
Just call your function and it will do the printing for you.
Advanced Concepts (Optional)
1- You can even include an if statement in your lambda although its stretching the practical mini use intentions of lambda, syntactically it’s correct and you may find useful applications for it.
Let’s see an example.
Example 11: Lambda with if
if statement in lambda
>>> a = lambda x: print(“Aloha!”) if x==”Hawaii” else print(“Ciao!”)
>>> print(“Hawaii”)
>>> print(“London”)
Aloha!
Ciao!
Example 12: Lambda with nested if
You can even have a nested if
inside a lambda
although it’s not a common use of functions and conditional statements at all.
>>> a = lambda x: print(“Aloha!”) if x==”Hawaii” else (print(“Salut”) if x==”Paris” else print(“Hi”)
>>> print(“Hawaii”)
>>> print(“Paris”)
>>> print(“London”)
Aloha!
Salut
Hi
Example 13: Month names
Here is a cool example that can be used to change data from integers to month names. This can be quite relevant for specific real world applications.
Imagine you have a list of integers that stand for months. Using map
and lambda
and calendar
library you can map these integers to month names.
calender.month_name[1]
will return “January“
>>> lst = lst=[1,2,3,4,5,6,7,4,3,2,5,11]
>>> lst = map(lambda x: calendar.month_name[x], lst)
>>> print(list(lst))
[‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘April’, ‘March’, ‘February’, ‘May’, ‘November’]
Tip: You can do the same with day names using day_name
function from calendar library.
calender.day_name[0]
will return “Monday“
We hope you liked this lambda
lesson.
Lambda
is very practical and for this reason it’s heavily utilized in a number of key industries such as: finance, data science, data visualization, scripting and cyber security as well as other fields.
Do you think you got the hang of lambda? We have online interactive lambda exercises in Python that might help you test your skills or master the concept!
Next Lesson: zip() function