Introduction to Anonymous function in Python

In this Python article, we will discuss anonymous function in detail and its use in python along with suitable examples.

1. What is an Anonymous function in Python?

Anonymous functions can be described as a function that does not have any name assigned to them. The term anonymous itself implies something unknown or hidden.

In python, we use the keyword lambda when we want to define an anonymous function.

Syntax

lambda arguments: statement(expression)

1.1. Characteristics of lambda function

  • In the lambda function, we may pass any number of arguments but it can have only one expression to evaluate and return.
  • We may use the lambda function whenever and wherever needed.
  • We can use the lambda function in various parts of the program.

Let’s take some simple examples to understand a single argument and multiple arguments in any lambda function.

# Single argument
val = 50
def value(val): return val-5

print(value(val))

# multiple argument
val_1 = 3
val_2 = 20
def value(val_2, val_1): return val_2-val_1

print(value(val_2, val_1))
Output
45
17

1.2. Lambda a function inside a function

lambda functions become powerful when we use the lambda function as an anonymous function in any function. But it’s better to use it for a short time period.

def easy_task(val):
  return lambda result: result+val


val_adder = easy_task(9)
print(val_adder(31))
Output
40

Here, we can see we have one function easy_task which accepts one argument. So we have used this function to add 9 to any number, we send through val_adder.

1.3. No parameter Lambda function

We can also create a no parameter lambda function.

# Example of no Parameter Lambda function
call_it = lambda:'Coding home!'

print(call_it())
Output
Coding home!

Read more: Parameters vs arguments in Python

1.4. Anonymous lambda function

We can also create an anonymous lambda function, which does not require the use of any variable to store it or execute it.

This type of function is executed just after the declaration.

Let’s implement a Lambda function that initialised and invoked at the same time and can never be used again.

result = (lambda val: val+val)(32)

print(result)
Output
64

Here, lambda val: val+val is an anonymous function with the argument in the parenthesis (32).

1.5. Lambda as a function parameter

In Python, just like the literals, we may pass functions as arguments. The usefulness of lambda functions comes in the picture when a function is to be sent as an argument to another function.

We can pass the lambda function, as an anonymous function just as a normal argument to another function.

Now, we will take a look at a function that accepts a lambda function as a parameter.

def with_lambda(x): return x(10)

print("Square With lambda ", with_lambda(lambda x: x*x))
print("Cube With lambda ", with_lambda(lambda x: x*x*x))
Output
With function  100
Square With lambda  100
Cube With lambda  1000

In the above example, we have implemented a function that accepts the lambda and runs it with a value.

This is a very basic example but this functionality can be used very effectively with a lot of scenarios as it provides the ability to pass in the functionality and not just the values which also follow the strategy design pattern.

We can also use lambda functions with different built-in functions like filter(), map() & reduce(). Let’s implement them one by one.


2. When to use Anonymous Function?

  1. For small and very trivial tasks which have very little complexity.
  2. For a function with only a single expression.
  3. When we want to implement the Lambda function with a scope limited to the current scope only.
  4. It’s useful when a function argument is another function such as map(), filter(), and reduce() functions. (Discussed in detail in next section)
  5. For temporary repetitive tasks.

3. How to use filter() with lambda function?

In python, we use filter() function to classically filter all the alike elements from a ‘sequence’. The filter() function intakes a function and an iterable as arguments. The function is applied to each element of the iterable. Examples of iterable are list, string, tuple. It filters out elements that return True.

Let’s take an example to understand the concept better. In this example we will have a list and we will filter the elements that are perfectly divisible by 2.

list_data = [3, 14, 21, 93, 64, 12, 37, 73, 69]
list_updated = list(filter(lambda n: (n % 2 == 0), list_data))
print(list_updated)
Output
[14, 64, 12]

4. How to use map() with lambda function?

In python, just like the filter() function the map() function intakes two arguments a function and an iterable. Here, the input function is applied on each value of the item label, and an iterator is returned with the updated values.

Lets implement two examples, first one return whether the number is divisible by 2 or not and the second example convert the string from lowercase to the uppercase.

list_data = [3, 14, 21, 93, 64, 12, 37, 73, 69] 
list_updated = list(map(lambda n: (n%2 == 0) , list_data))
print(list_updated)

pet_list = ['dog', 'cat', 'parrot', 'rabbit', 'mouse', 'monkey']
cap_pet_list = list(map(lambda pet: str.upper(pet), pet_list))
print(cap_pet_list)
Output
[False, True, False, False, True, True, False, False, False]
['DOG', 'CAT', 'PARROT', 'RABBIT', 'MOUSE', 'MONKEY']

5. How to use Reduce with lambda function?

In python, just like the above two, the reduce() function intakes two arguments, a function and an iterable. We can also pass the third parameter which is an initializer, sometimes we need this to initialize the value of the accumulator. Reduce function is applied over the pair of values repeatedly until it is exhausted and the final value is returned.

We need to import the reduce() function from the  functools module. 

Let’s implement an example to find the sum of elements in a list.

from functools import reduce
list_data = [3, 14, 21, 93, 64, 12, 37, 73, 69]
add_all = reduce((lambda n, m: n + m), list_data)
print("Sum elements in list is - ", add_all)
Output
Sum elements in list is - 386

6. Conclusion

In this article we have covered everything about

  • What is meant by the Anonymous function along with various examples?
  • Various types of lambda functions and how we can use them.
  • Use of Filter, Map & Reduce with lambda function along with suitable examples.

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x