- Python lambda – Anonymous Function
- When to use Anonymous Function?
- Lambda Function with map()
- Lambda Function with filter()
- Lambda Function with reduce()
- Python lambda function with no arguments
- Conclusion
- References:
- Python Lambda Function without Arguments
- Examples
- 1. Lambda Function without arguments that always returns “Hello World”
- 2. Lambda Function without arguments that always returns 3.14
- Summary
- How to Call Functions in Python: A Complete Guide (Examples)
- 1. How to call a function without arguments in Python
- 2. How to call a function with arguments in Python
- 3. How to call a function with keyword arguments in Python
- 4. How to call a function with any number of arguments in Python
- 5. How to call a function with any number of keyword arguments in Python
- 6. How to call a function from another file in Python
- Conclusion
- Further Reading
Python lambda – Anonymous Function
Let’s say we have a function to get the area of a rectangle.
def area_of_rectangle(l, w): return l * w print(f'Area of Rectangle (4, 5) is')
Let’s create an anonymous function using the lambda keyword to get the area of the rectangle.
rectangle_area = lambda x, y: x * y print(f'Area of Rectangle (4, 5) is')
When to use Anonymous Function?
- For small trivial tasks with not much complexity.
- When the function has only a single expression.
- For repetitive tasks that are temporary in nature.
- When you want the function scope to be limited to the current scope only.
- It’s useful when a function argument is another function such as map(), filter(), and reduce() functions.
Lambda Function with map()
The map() function takes a function and an iterable as the arguments. The function is applied to every element in the iterable and the updated iterable is returned.
Let’s say we have a list of integers. We have to create a new list by multiplying every element with 10. We can use lambda function here rather than creating a function for this single use case.
list_numbers = [1, 2, 3, 4] list_numbers = map(lambda x: x * 10, list_numbers) for num in list_numbers: print(num, end=" ")
Lambda Function with filter()
The built-in filter() function takes a function and an iterable as the argument. The function is applied to each element of the iterable. If the function returns True, the element is added to the returned iterable.
Let’s say we have a list of integers and we want to remove all the odd numbers. The final list should have only even integers. We can use filter() function here with the lambda function.
list_numbers = [1, 2, 3, 4, 5, 6] list_numbers = filter(lambda x: x % 2 == 0, list_numbers) for num in list_numbers: print(num, end=" ")
Lambda Function with reduce()
The reduce() function is present in the functools module. This function takes a function and a sequence as the argument. The function should accept two arguments. The elements from the sequence are passed to the function along with the cumulative value. The final result is a single value.
Let’s say we have a list of integers and we want to get the sum of all of its elements. We can use the reduce() function here with the lambda function.
from functools import reduce list_ints = [1, 2, 3, 4, 5, 6] total = reduce(lambda x, y: x + y, list_ints) print(f'Sum of list_ints elements is ')
Python lambda function with no arguments
Someone asked me if we can have a lambda function without any argument?
Yes, we can define a lambda function without any argument. But, it will be useless because there will be nothing to operate on. Let’s have a look at a simple example.
get_5 = lambda: 5 print(get_5()) # 5
Since the lambda function is always returning the same value, we can just assign it a variable. Using lambda function without any argument is plain abuse of this feature.
Conclusion
Python anonymous functions are created using the lambda keyword. They are useful when a function argument is another function. It’s mostly used to create simple utility functions for one-time use.
References:
Python Lambda Function without Arguments
In Python, you can define a lambda function without any arguments by using an empty parameter list.
For example, consider the following lambda function.
This lambda function has no arguments, and when you call this lambda function, it always returns «Hello World».
Therefore, a lambda function without arguments returns a specified constant value.
Examples
1. Lambda Function without arguments that always returns “Hello World”
In the following program, we define a lambda function without any arguments, and that always returns a string value of «Hello World». We shall assign the lambda function to a variable named greeting. Call the lambda function with greeting() and print the returned value.
Python Program
greeting = lambda: "Hello World" # Call the lambda function result = greeting() print(result)
2. Lambda Function without arguments that always returns 3.14
In the following program, we define a lambda function without any arguments, and that always returns a floating point value of 3.14.
We shall assign the lambda function to a variable named pi.
Python Program
pi = lambda: 3.14 # Call the lambda function result = pi() print(f"PI is ")
Summary
In this tutorial of Python Lambda Functions, we learned how to define a lambda function without arguments, and does this lambda function work, with the help of example programs.
How to Call Functions in Python: A Complete Guide (Examples)
To call a function in Python, add parenthesis after the function name.
For example, if you have a function called greet , you can call it by:
And if the function takes arguments, specify them inside the parenthesis:
Let’s take a deeper dive into functions and how to call them in Python. More specifically, we are going to take a look at how to call functions:
- With no arguments.
- With arguments.
- With keyword arguments.
- With any number of arguments.
- With any number of keyword arguments.
- From another file.
1. How to call a function without arguments in Python
This is a basic example of how to call a function in Python.
A function that takes no arguments can be called by adding parenthesis after the name of the function.
For example, let’s create a function greet .
def greet(): print("Hello world!")
And now you can call the function by:
This results in the following output to the console:
2. How to call a function with arguments in Python
It is common for a function to accept an argument or arguments to work with.
To call a function that takes arguments, specify the arguments inside the parenthesis when calling the function.
For example, let’s create a function that accepts one argument:
def greet(name): print("Hello,", name)
And let’s call this function:
This results in the following output to the console:
Let’s also demonstrate functions that take more than one argument:
def greet(firstname, lastname): print("Hello,", firstname, lastname)
Now you can call the function by:
This produces the following output:
3. How to call a function with keyword arguments in Python
Python functions can accept two types of arguments:
When it comes to positional arguments, order matters.
For example, in the previous example, the function took two positional arguments:
def greet(firstname, lastname): print("Hello,", firstname, lastname)
The function expects these arguments to be in the right order. The first argument should be the first name and the last argument should be the last name.
However, if you pass the arguments as keyword arguments, you may swap their order freely.
A keyword argument is an argument where you name the argument you pass into a function.
Let’s call the greet function from the previous example by providing it with the arguments as keyword arguments:
greet(lastname="Jones", firstname="Nick")
As you can see, using keywords allowed you to swap the order of the arguments.
4. How to call a function with any number of arguments in Python
Sometimes you don’t know how many arguments you want to pass into a function. Thus, it is possible to call a function with an arbitrary number of arguments.
To demonstrate, let’s create a function that accepts any number of arguments. To make this possible, the function argument needs to be preceded by an asterisk * :
def greet(*args): for name in args: print("Hello,", name)
Now you can call the function with any number of arguments
greet("Nick") greet("Matt", "Sophie", "Jon")
Hello, Nick Hello, Matt Hello, Sophie Hello, Jon
You can also pass the arguments as an array. But if you do this, add the asterisk before the array to unpack the arguments for the function:
Hello, Matt Hello, Sophie Hello, Jon
5. How to call a function with any number of keyword arguments in Python
You may not know how many keyword arguments to pass into a function. But this is no problem. Python lets you design functions in such a way that you can pass any number of keyword arguments into it.
To demonstrate, let’s create a function that accepts any number of keyword arguments. To make this possible, the argument needs to be preceded by a double asterisk ** :
def greet(**kwargs): for literal, name in kwargs.items(): print("Hello,", name)
Now you can call the function with any number of keyword arguments, and name the arguments however you like:
greet(name="Marie") greet(name="Jane", otherName="Ann")
Hello, Marie Hello, Jane Hello, Ann
You can also call this function by passing a dictionary as an argument. If you do this, remember to unpack the dictionary with the double-asterisk **:
6. How to call a function from another file in Python
To call a function from another Python file, you need to import the file and call the functions from it.
Here is an illustration where a function is called from another file:
If you want to import a specific function from another file, you can specify the name of the function in the import statement as seen above.
But if you want to import all the functions from another file, use * in the import statement.
Conclusion
Today you learned how to call a function in Python.
To recap, functions allow for grouping useful code and logic into a reusable block of code. When you call a function in Python, you’re running the code inside the function.
In Python, you can call functions with:
Thanks for reading. I hope you enjoy it.