Lambda Functions in Python : Enhancing Efficiency and Readability

Lambda Functions in Python : Enhancing Efficiency and Readability

A Comprehensive Guide for Mastering Lambda Functions in Python

In this article, we'll learn in-depth about Lambda functions in Python programming and its use case.

Check out the previous comprehensive article on Python Functions titled: Efficiency and Reusability : Harnessing the Power of Functions in Python in this Python series.

Lambda Function In Python

Lambda function is an anonymous function that can take arguments with one expression. IIFEs are Immediately Invoked Function Expressions. Lambda keyword in Python can be used to create IIFEs.

It can be referred to as : anonymous functions, lambda expressions, lambda abstractions.

In python the lambda keyword is used to create an anonymous function

Structure of Lambda Function

lambda argument(s) : expression
  • lambda: Python keyword for defining an anonymous function.

  • argument(s): the value(s) indicated after the lambda keyword required for the anonymous function.

  • colon: the colon indicates the beginning of the expression

  • expression: the body of the lambda function or single line of code on what the anonymous function performs.

Difference between Standard Function and Lambda Function

A Python Standard Function: begins with the def keyword and easy to understand, contains multiple lines of code, documentation with the docstring, slower than lambda function.

A Python Lambda Function: begins with the lambda keyword, has single use, defined in single line (expression), can be named or remain anonymous .

Example of Lambda Function

  • Calling Lambda function at the point of definition
#calling the lambda function without argument
(lambda : print('Calling lambda function at the point of definition'))()

# calling the lambda function with one argument name
(lambda name : print(f'My name is:{name}'))("Alemsbaja")
  • Assigning Lambda function to a variable with single argument

Lambda function can be assigned to a variable since it has an expression or can return a value which will be used to invoke (call) it.

lambda_fxn = lambda name : print(name.upper())
lambda_fxn("Alemsbaja")
  • Assigning Lambda function to a variable with Multiple arguments
stu_details = lambda name, location : print(f'The student name is:{name} from {location}')
stu_details("Alemsbaja", "Earth")

#The student name is:Alemsbaja from Earth

Lambda function can be used with High Order Functions - map(), filter(), reduce() etc..

  • Lambda function in map()

A map() function takes in a lists an argument and return a new list. It essentially allows for manipulation of each item on the list during iteration.

For example: the upper case and length of each item in the names list will be returned from the map function with combination of lambda (anonymous) function.

names = ["alemsbaja", "raph", "bonger", "dev", "taylor", "ur"]
print(list(map(lambda item: [item.upper(), len(item)], names)))

#[['ALEMSBAJA', 9], ['RAPH', 4], ['BONGER', 6], ['DEV', 3], ['TAYLOR', 6], ['UR', 2]]
  • Lambda function in filter()

A Filter() function is a function that takes in a lists and returns the items that execute to be true based on the condition defined. This can be achieved with the lambda function.

Let's assume we have a list of names and we want to return names with characters higher than 5 only.

names = ["Alemsbaja", "Raph", "Bonger", "Dev", "Taylor", "Ur"]
print(list(filter(lambda item: (len(item) > 5), names)))

#['Alemsbaja', 'Bonger', 'Taylor']
  • Lambda function with reduce() from functools module

The reduce() function takes in a list and return a value after performing computations on each item in the list.

For example: let's sum up the numbers in a list using the reduce and anonymous function.

import functools
# this scores could be a column in an excel sheet for Data analysis
#col['scores']
scores = [60, 75, 90, 45, 88, 45, 12]
print(functools.reduce(lambda numb1, numb2: numb1 + numb2, scores))

The lambda function can come handy at any point of developing applications even in data science using the higher order functions filter(), map(), pandas apply() function, reduce().

Conclusion

A Lambda function is an anonymous function with a single expression. It is most suitable for a brief immediate use within a function or program. It's a bad practice, according to the PEP 8 style guide for Python code to assign a lambda function to a variable.

If you're looking forward to developing applications in Python using the OOP (Object-oriented programming), the major concepts are simplified on my blog here.

Find this helpful or resourceful?? kindly share and feel free to use the comment section for questions, answers, and contributions.

💡
Follow me on Hashnode: Alemsbaja X: Alemsbaja | Youtube: Tech with Alemsbaja to stay updated on more articles

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!