There is a function in Python named the lambda function that is very useful for writing anonymous functions. Now you are wondering why it is anonymous. So, it has the feature of creating a function without a name but with an expression. This is the advanced concept of Python, where you can define a function spontaneously without any doc-strings or function header. It encourages the writing of concise and to-the-point expressions, mostly when inline expression and logic are required within the expression. Therefore, in this article, we will discuss the basic understanding of the lambda function, its syntax with examples, and when and how to use this advanced feature. Let's get started!
Understanding Lambda Functions
Definition of Lambda Functions
A lambda function is one of the simplest ways to define a function in Python. It is anonymous, defined without a name, and does not contain the def keyword. It can accept any number of arguments but can have only one expression.
Syntax for Defining Lambda Function
The lambda function is always defined using the lambda keyword followed by the arguments and the expression we want to evaluate. The following is the syntax of the lambda function:
lambda arguments: expression
Characteristics and Limitations of Lambda Function
One of the features of many programming languages is the lambda function, known as an inline function or lambda expression. This feature allows you to write the function without any signature and expressed in a single line of code. They are like user-defined functions. Here are some of the characteristics of the lambda function:
- Lambda functions are not created in the traditional way which means, the function has no name making them anonymous functions.
- Lambda functions are suitable for simple logical operations because of their simple syntax and inline nature, allowing direct use of logic without traditionally defining a complex control structure or multiple statements.
- It is preferred when we want only one expression in return. A lambda function reduces the need to define a separate named function when a single operation is required.
- A lambda function is also used as a parameter for different functions such as map and filter. They are considered first-class citizens in Python because they can be stored as variables and passed as arguments to other function signatures.
- They are flexible when taking any number of arguments separated by commas with different types of return values.
Although the lambda function provides the concise and advanced features of defining functions in Python with its inline nature, it has some limitations that need attention. So, let's discuss them:
- Lambda functions are restricted to only one expression to ensure that they focus on a single task. For complex logic and multiple statements, they cannot deal with such cases efficiently.
- The doc-string is a feature used to explain the purpose of the function before its implementation. However, we cannot explain the inputs, operations, and outputs in lambda functions because of their inline nature.
- In addition, lambda functions are not used when the function declaration requires multiple lines of code. In addition, they are quite limited in functionality, such as loops or nested within other expressions.
Basic Syntax and Usage
Introduction to Basic Syntax of Lambda Functions
Mostly, lambda functions are used when a small function is temporarily required within the program. To use the lambda function in the program, we need to understand its syntax. Its syntax is divided into four components:
- Lambda: Keyword used before the implementation of the lambda function.
- Arguments: Take as many arguments as required, where each argument or parameter is separated by a comma.
- Colon: Acts as a separator between the arguments and the expression.
- Expression: Evaluate single valid expressions, execute, and return the function result.
Illustration of Simple Lambda Functions for Mathematical Operation
Now, let's discuss and illustrate the lambda function with a simple mathematical operation example of the addition of two numbers.
#addition lambda function with 2 arguments
addition = lambda x ,y: x * y
#prints the result
print(addition(7,7))
For immediate execution of the lambda function, parentheses can be used around the lambda function. This makes it an immediately invoked function expression.
Another example of multiplication of 3 numbers is where we have three numbers as an argument and have one single expression.
#multiplication lambda function with 3 arguments
multiply = lambda x ,y, z: x * y * z
#prints the result
print(multiply(7,7,9))
Lambda Functions with Built-in Functions like "map", "filter", and "sorted"
As we discussed, lambda functions are used as small functions or arguments for higher functions. These higher functions are built-in Python functions such as map(), filter(), sorted(), and reduce(). We can use the lambda function as a single expression to define simple logic or operations without defining a separate function. This approach provides clarity and conciseness in the program when the function is temporarily required. Let us understand each with a code example.
1. filter(): Using the lambda function with the filter module to filter the values of the list and extract the positive numbers.
#lambda function with filter module to extract positive numbers
num = [1,57,38,-97,-56,9,2]
numbers_pos = filter(lambda x: x > 0, num)
#prints the result
print(list(numbers_pos))
2. map(): Using the lambda function with the map module to alter all items of the list with the specified expression.
#lambda function with map module to alter the numbers
num = [1,57,38,8,56,9,2]
numbers_pos = map(lambda x: x + 7, num)
#prints the result
print(list(numbers_pos))
3. sorted(): Using the lambda function with the sorting module to sort the elements in the list.
#lambda function with sort module to sorting the numbers
num = [1,57,-38,-8,56,9,2]
numbers_dessort = sorted(num, key = lambda n : -n) #-n indicate the list sorted in descending order
numbers_ascsort = sorted(num, key = lambda n : n) #n indicate the list sorted in ascending order
#prints the result
print("In Descending Order:", list(numbers_dessort))
print("In Ascending Order:", list(numbers_ascsort))
Lambda Functions VS Regular Functions
Comparison Between Lambda Functions and Regular Named Functions
We now discuss the characteristics and limitations of the lambda function. Now, let us compare it with the regular function in different aspects. Regular and lambda functions are both used in the programming world, and each has its advantages and uses.
1. Syntax
- A regular expression is defined using the "def" keyword followed by the name and parameters within parentheses and the block of code.
- Lambda functions are defined using the lambda keyword followed by the parameters, colon, and valid expression.
#Regular Function
def square(x):
return x*2
#Lambda Function
square = lambda x : x*2
2. Name
- In a regular function, the name is mandatory given to the function and is used to call it everywhere in the code.
- Lambda functions as anonymous functions do not require any specified name because they are often directly called where it's defined.
3. Parameters
- Regular functions can have multiple parameters separated by commas, specified by the parentheses.
- The lambda function can also have multiple parameters specified by a colon as a separator.
4. Function Body
- Regular expression deals with the multiple pieces of code within the function definition.
- The lambda function deals with only a single valid expression that is evaluated against the parameters and returns the result.
5. Return statement
- The regular function uses the return statement to return the values from the function.
- The lambda function does not require a return statement.
6. Reusability
- We can use regular functions multiple times by just calling the function name without explicitly using the code repeatedly.
- The lambda functions are inline and have a specific task that we cannot reuse in other parts of the code.
When to Use Lambda Functions and When to Use Regular Functions?
Python developers mostly use the lambda function when they want to add an inline expression, which is used only once. This function cannot be called at other places in the program and is invoked only when the code is compiled. However, if we compare its use case with that of a regular function, the regular function is the traditional way of defining the function. They are mostly used for writing blocks of code that handle complex logic and are required at multiple locations.
Example Demonstrating the Readability and Conciseness of Lambda Functions
To comprehend the readability and conciseness of using the lambda function, I will demonstrate the conditional operations with the simple if-else in the lambda function expression. Here, I am mapping the list of people of age with eligibility to cast a vote.
#lambda function with map module and conditional statement to alter the eligible one
people_age = [12,17,38,45,56,19,22]
eligibility = map(lambda age: "Eligible" if age >= 18 else "Not Eligible", people_age)
#prints the result
print(list(eligibility))
Remember, we can nested multiple conditions like if-elif-else in the expression but try to avoid its incorporation as this affects the code readability.
Advanced Usage of Lambda Function
Explanation of Using Lambda Functions with Higher-Order Functions
The higher-order function is an advanced and popular concept in Python. It is a function that takes one or more functions as arguments. Also, said to a function that returns a function as its result. They use the lambda function as an argument to evaluate the expression. These higher-order functions are: sorted(), max(), filter(), reduce(), and so on, are built-in modules in Python. Let's define the higher-order function with a lambda function.
The lambda expression, an anonymous function, and lambda function are names used interchangeably.
#lambda with higher order function
higher_funtion = lambda num, fun: num + fun(num) #takes the num and fun as two arguments
# print the num and fun expression with value
print("The Result is", higher_funtion(70, lambda num : num % 3 ))
Illustration of Lambda Functions as Arguments to Functions like "sorted" and "max"
Lambda functions are quite popular for use as arguments with many built-in functions. Here, I illustrate the lambda function as an argument for higher-order functions one by one.
1. max(): Returns the maximum value from the iterable object i.e., list, tuples, and dictionary.
#lambda function with max module to find the maximum number
num = [1,57,-38,-8,56,9,2]
max_number = max(num, key = lambda n : n)
#prints the result
print("The Higher number is:",max_number)
2. min(): Returns the minimum value from the iterable object i.e. list, tuples, dictionary. Here, I am using the list in the example
#lambda function with min module to find the minimum number
num = [1,57,-38,-8,56,9,2]
min_number = min(num, key = lambda n : n)
#prints the result
print("The Lowest number is:",min_number)
3. reduce(): Returns single values after performing the computation on the iterable values.
from functools import reduce
#lambda function with reduce module
num = [1,7,8,4,6,9,2]
#this reduce the list based on the espression
multiple = reduce(lambda n, m : n * m, num)
#prints the result
print("The Result is:",multiple)
4. zip(): Combines multiple lists based on the expression and returns a single list or iterable.
#lambda function with zip module
num = [1,7,8,4,6,9,2]
num2 = [2,5,7,3,7,9,3]
#this zip the two list into one based on the expression
addition = map(lambda n: n[0] + n[1], zip(num, num2))
#prints the result
print("The Result is:",list(addition))
Functional Programming Paradigm
Introduction to Functional Programming Paradigm and its Relevance to Lambda Functions
Function programming is the programming technique that avoids side effects in your program by performing computation mainly through the evaluation of all functions. It relies heavily on immutable data structures. It is a programming style just like OOP that can reduce the likelihood of bugs in your code. Furthermore, it provides many features, one of which is lambda functions. However, the lambda function is used as a functional programming tool to create small functions that will be used once in a program with no need to explicitly define their name and proper function signature.
Explanation of Pure Functions, Side Effects, and Immutability
Pure functions give the same output every time the function executes with the given input without any side effects. These functions do not have any side effects like the function that followed the imperative paradigm. Instead, they preserve the definition and logic of the function. They are immutable because once the data are defined, we cannot change them, which is primarily done to avoid side effects.
Demonstration of Using Lambda Functions in Functional Programming Style
Let's demonstrate an example of a lambda function in functional programming style. Here, I create a list of strings and use the sorted() module with the lambda function to sort the list based on their length. Convert the string of the list into uppercase using the map() module.
list_string = ["hello", "python", "programming", "world", "functional"] #list of string
#sort the list based on their length
string_sort = sorted(list_string, key = lambda n: len(n) )
#prints the result
print("The Result is:",string_sort)
#alter the string in uppercase
uppercase_words = list(map(lambda n: n.upper(), list_string))
print("Uppercase of list is:", uppercase_words)
Wrapping Up
In conclusion, we discussed the advanced concept of Python, which includes lambda functions. This function is helpful when you want to write a one-liner function in your program that is in one place only. They ensure an immediate function-invoked expression approach. We also see practical examples alongside the Python code. We learned how it differs from regular functions, and each has its own use case and advantages. So, this is a good way of exploring functional programming in Python. Thank you for reading this guide. Happy Coding!
Reference
Lambda Function in Python