Lambda Functions in Python

Lambda function in Python is an anonymous function. They are a short and powerful functional programming technique in Python. Here is a complete tutorial on the concept of Lambda functions.

Topics Covered:-

1) What is a Lambda Function?

2) How to write a Lambda function in Python?

3) Why use Lambda functions?

4) How to add more logic to lambda functions?

Lambda functions in python, tend to intimidate people way more than they should. They are very cool and short way of generating python function objects. Lambda originally comes from the lisp language. They are also called anonymous functions. It’s because by using lambda expression you return the function without assigning it any name. Like in functions we use the keyword def, in lambda functions, we assign the keyword lambda.

Screenshot 2018-12-27 at 10.38.45 PM

The way we mention parameters inside the parentheses of a function to pass arguments, in lambda we would directly add those arguments after the lambda keyword. Finally, the way we return expression in a normal function for lambdas, we would directly write the return expressions without using any keyword.

“””
Practice Lambda functions
“””

def square(x):
return x * x

# To convert this into a lambda function

square_2 = lambda x: x * x

print(square(2))

print(square(5))

This is how lambda funtions work.

Now, you can have a lambda function nested inside a normal function. Let’s me give an example:

“””
Practice Lambda functions
“””

def greetings():
start_word = “Hello”
greet = lambda y: start_word + str(y)
return greet

result = greetings()
print(type(result))
print(result(” Nagilla”))

Now why use Lambda?

Function objects returned by lambda run the same way as those created and assigned by defs, but there are few things that make lambda really useful in specific roles:

  1. Lambda can be embedded in places where “defs” can’t be used.
  2. Function names could clash in your programs.

Lambdas are single line of expression

Since they are single expression, it is difficult to get as much logic as you would want into a lambda function. Therefore to implement more logic, convert statements as expression-based equivalents inside the lambda function. Let’s see an example:

“””
Practice Lambda functions
“””
#
# if a:
# b
# else:
# c
#
# b if a else c

def greetings():
start = “Hello”
greet = lambda x, y: start + ” Mr.” + str(x) if y == ‘M’ \
else start + “Miss ” + str(x)
return greet

result = greetings()
print(type(result))
print(result(” Nagilla”, “M”))

We can also have loops inside of a lambda function. For that purpose we can embed built-in python functions like map, filter, reduce and list comprehensions into the lambda function.

Let’s understand what these built-in python functions are:

The map method allows you to apply a specific operation or a function to each element in a sequence.

Screenshot 2018-12-27 at 11.20.06 PM

Let’s say you want to multiply all the numbers in the list by 2. In this case, instead of writing a for loop, we can use the map method to collect the required results.

Screenshot 2018-12-27 at 11.22.23 PM

Example for map built-in function:

lst = [1, 2, 3, 4]

def add_1(lst):
updated = []
for element in lst:
updated.append(element+1)
return updated

print(add_1(lst))

def add_1_map(x):
return x+1

result = map(add_1_map, lst)
print(result)

for element in result:
print(element)

print(list(result))

result1 = map(lambda x: x+1, lst)
print(list(result1))

The filter method in python is used to select relevant items from a sequence. It selects items from a sequence passes them through a function and returns the filtered sequence satisfying the condition.

Screenshot 2018-12-27 at 11.26.01 PM

An example would be getting a list with only positive integers from a list with a mix of different integers.

Screenshot 2018-12-27 at 11.28.32 PM

Example for filter built-in function:

lst = [-4, -2, 0, 3, -5, 10]

def get_postive_numbers(lst):
updated = []
for element in lst:
if element > 0:
updated.append(element)
return updated

print(get_postive_numbers(lst))

Now, there is an alternative to this, by using the filter built-in method.

def get_postive_numbers_filter(x):
return x > 0

result = filter(lambda x: x>0, lst)
print(list(result))

The reduce built-in method doesn’t return a sequence, it returns one result.

Screenshot 2018-12-27 at 11.30.27 PM

It takes the first two elements of a sequence performs the operation and calculates the result then takes the third element and performs the operation with the result of the first two and so on.

Screenshot 2018-12-27 at 11.33.18 PM

Screenshot 2018-12-27 at 11.33.07 PM

At the end it just returns the result.

Screenshot 2018-12-27 at 11.34.50 PM

We could think of this similar to how a for loop would work.

Example of reduce built-in function:

lst = [-4, -2, 0, 3, -5, 10]

def get_sum(lst):
sum = 0
for element in lst:
sum += element
return sum

print(get_sum(lst))

Now, How to do this using reduce?

from functools import reduce

lst = [-4, -2, 0, 3, -5, 10]

# def get_sum(lst):
# sum = 0
# for element in lst:
# sum += element
# return sum
#
#print(get_sum(lst))

def get_sum_reduce(x, y):
return x + y

result = reduce(lambda x, y: x + y,  lst)
print(result)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s