Lesson 11: Lambda

Lambda, sometimes also called anonymous function, is a perfect way to handle a mini function necessity, without creating blocks or sometimes without naming your function, in one line.

When you need a proper user defined function creating a block with def keyword works great.

But the necessity for lambda arises from the situations where you just need a one time quick solution for your user defined function.

Although lambda syntax can be slightly confusing in the beginning, it can be quite handy once you get a hang of it.

Function : N/A

This lesson doesn’t introduce a new function.

Used Where?

  • As a quick alternative to a regular user defined function.
  • As an argument for some other functions:
    • .sort()
    • sorted()
    • filter()
    • map()
    • reduce()

Syntax do(s)

1) Start your argument with keyword lambda

2) Then variable name followed by colon(:)

3) Last part is 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 your lambda

Lambda first, variable second, colon third and statement forth and last.

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.
You’ve created a mini lambda function.

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 and/or with the variable.

Example 3: lambda with logical expression

>>> a = lambda x: x%5==0
>>> print(a(555))
>>> print(a(222))

True
False

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

You can also pass two arguments to your lambda:

>>> 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 lambdafunction as an argument inside .sort()‘s parenthesis.

>>> lst = [1, 5, 66, 7]
>>> lst.sort(key=lambda x: x)
print(lst)

[1, 5, 7, 66]

if you’d like to use a function as an argument in .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.

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, 11, 71, 12]

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.

Example 10: filter() with lambda

Another function that works well with lambda, filter() is also similar to the map() function syntax wise. 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

Exercise 11

Lesson 12

zip()

Indian_Wigwam_in_Lower_Canada_(1848_)_Cornelius_Krieghoff


Cornelius Krieghoff

Indian Wigwam in Lower Canada

Indian Wigwam in Lower Canada by Cornelius Krieghoff