Python lambda with no arguments

Python Lambda Function: Secret to Anonymous and Concise Code Read it later

In Python, developers use lambda functions as anonymous, inline functions that can be defined and called on the fly without needing a separate function. Programmers commonly use lambda functions to pass functions as arguments to higher-order functions or to define simple, one-time-use functions.

In this article, we’ll be exploring Python lambda functions in-depth and how they work. We’ll cover their syntax, use cases, advantages, and limitations. Furthermore, we’ll provide practical examples to help us understand how to use lambda functions effectively in Python.

Check out our other blogs on Python development, including Python decorators, generators, enumerate function and list comprehension to enhance your Python skills.

Python Lambda Function Syntax

People know the Lambda function in Python as an anonymous function that can have any number of arguments but can only contain expressions in its body.

Let’s take a closer look at the syntax of a lambda function and explore each characteristic in detail:

lambda arguments: expression

Expressions Only

A lambda function can only contain expressions, which means it cannot include statements, such as print statements or assignments, in its body.

Читайте также:  Меняем цвет шрифта при помощи HTML

If we try to add a statement in a lambda function, it will raise a SyntaxError.

# Invalid syntax lambda x, y: print(x + y) # Valid syntax lambda x, y: x + y

One Line, One Shot

We write a lambda function as a single line of execution, which means we cannot include multiple lines of code in it.

However, we can include multiple expressions by separating them with commas.

Example of invalid Python lambda function syntax:

# Invalid syntax lambda x, y: x += 1 y += 1 return x + y # Valid syntax lambda x, y: (x + 1, y + 1)

Inference over Annotation

A lambda function does not support type annotations, which means we cannot specify the type of arguments or the return type of a lambda function.

However, Python can infer the type of arguments and the return type of a lambda function.

# Invalid syntax lambda x: int: x + 1 # Valid syntax lambda x: x + 1

Lambda on the Fly (IIFE)

We can immediately invoke or execute a lambda function, which means we can call it as soon as we define it.

This is also known as an Immediately Invoked Function Expression (IIFE) in Python.

# Invalid syntax (lambda x, y: x + y)(10, 20) # Valid syntax result = (lambda x, y: x + y)(10, 20) print(result)

Python Lambda Function Arguments

Python lambda functions can take any number of arguments, but they can only have a single expression. Developers often use lambda functions as a substitute for named functions when the function’s functionality is simple and a named function would be excessively complex.

The arguments to a lambda function are passed in the same way as they would be for a named function. They can be positional arguments, default arguments, variable-length arguments, or keyword arguments.

No Arguments, No Problem

A lambda function in Python can have any number of arguments, including zero arguments. Lambda function with no arguments performs a simple operation without needing any inputs.

# a lambda function that returns the string "Hello, World!" hello = lambda: "Hello, World!" print(hello()) # Output: Hello, World!

We use lambda functions with no arguments when we need to perform a simple operation that does not require any input from the user. We can use them in scenarios where we need to pass a function as an argument to another function, but the function itself does not require any arguments.

Positional Arguments

The lambda function takes positional arguments based on their position. This means that the first argument in the lambda function definition corresponds to the first argument passed to the function, the second argument in the lambda function definition corresponds to the second argument passed to the function, and so on.

# a lambda function that takes two positional arguments and returns their product product = lambda x, y: x * y print(product(2, 3)) # Output: 6

In the above example, we have defined a lambda function product that takes two positional arguments and returns their product. We have called this lambda function and passed two arguments 2 and 3.

Default Arguments

The lambda function specifies a default value for an argument using default arguments when the caller does not pass the argument. If the caller does not pass an argument to a lambda function that has a default value, the function uses the default value.

# a lambda function that takes one positional argument and one default argument power = lambda x, y=2: x ** y print(power(3)) # Output: 9 print(power(3, 3)) # Output: 27

In the above example, we have defined a lambda function power that takes one positional argument and one default argument. If we do not pass the second argument, the default value will be 2. We have called this lambda function with only one argument in the first case, and with both arguments in the second case.

Variable-Length Arguments

In a lambda function, we use variable-length arguments to accept an arbitrary number of arguments. We denote the variable-length argument by an asterisk (*) before the argument name. This enables the lambda function to accept any number of arguments that someone passes to it.

# a lambda function that takes a variable-length argument and returns the sum of all the numbers sum_lambda = lambda *args: 0 if len(args) == 0 else args[0] + sum_lambda(*args[1:]) print(sum_lambda(1, 2, 3, 4)) # Output: 10

In the above example, we have defined a lambda function sum that takes a variable-length argument and returns the sum of all the numbers passed to it.

Keyword Arguments

Lambda functions use keyword arguments to pass arguments by name rather than position. This allows the caller of the function to pass arguments in any order, which can make the function easier to use.

# a lambda function that takes two keyword arguments and returns their difference difference = lambda x, y: x - y print(difference(y=2, x=5)) # Output: 3

Python Lambda vs. Regular Function

Python offers two primary ways to define functions: Lambda functions and regular functions. While they share a common purpose of executing code, there are some key differences between the two.

Let’s compare Lambda functions and regular functions side by side:

Источник

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.

Источник

Python Lambda Functions

In Python, we can create functions known as anonymous functions which don’t have a name. A lambda function is a type of anonymous function defined using the lambda keyword.

We know that a regular function is defined using the def keyword. A lambda function is defined using the lambda keyword and hence got its name.

But why would we ever use a lambda function?

Suppose you have created a function having a single statement in its body and that function is called at only one place in your program. In this situation, it doesn’t make much sense to create such short functions for one time use. This is where we can use lambda function in place of regular function. We can directly define the lambda function at the place where it is required instead of defining a function separately and then calling it. This will make the code more readable.

Now the question is why would I ever need a function if I need it only one place and it contains only a single statement? There may be cases where a different function needs a function as their input. In those cases, a lambda function would be helpful.

Let’s see what lambda functions are and then you will understand what we are talking about.

We will discuss more use cases and limitations of lambda functions later.

Using lambda Functions in Python

Before learning to create lambda functions, look at the following function.

def identity(x): return x + 1 

The function identity() has just one statement and it simply returns the parameter that it receives after incrementing it by 1.

This function can be written in the form of a lambda function as shown below.

This function created using the keyword lambda doesn’t have a name and is called a lambda function. It has one argument x that is passed to the function. It has one expression x + 1 which is evaluated and returned. Thus, this lambda function will receive an argument x , add 1 to it and then return the result.

Now let’s look at the syntax of a lambda function.

Syntax of lambda function

lambda arguments: expression

lambda is a keyword which is used to define lambda functions.

arguments are the same arguments which we pass to regular functions. There can be any number of arguments in lambda functions.

expression is some expression which is evaluated and returned. There can be only one expression in a lambda function.

Now let’s look at some examples of lambda functions.

Examples of lambda function

The following example has a function square() which takes a number and returns the square of that number.

def square(x): return x**2 print(square(3)) 

Now suppose this square() function is called at only one place in the program. Then instead of defining and calling it, we can directly define a lambda function at the place where it is called. Let’s see how.

In this example, we defined a lambda function, passed a value to it and printed the value returned by the function.

lambda x: x**2 — In this function, x is the argument and x**2 is the expression. The function receives the argument x , evaluates the expression x**2 and then returns the result of the evaluation.

(3) — The value 3 is passed to the function, or we can say that 3 is the argument passed to the function. The values passed to a lambda function are enclosed within parentheses ( ) and written after the lambda function definition.

Did you notice that the value of the expression is getting returned even without using the return keyword? In lambda functions, the value of the expression always gets returned, so make sure to write the expressions accordingly.

We can also assign the lambda function to a variable so that we can use it anywhere by directly passing the variable name.

square = lambda x: x**2 print(square(3)) 

In this example, the same lambda function is created and assigned to a variable square . The value 3 is passed to the lambda function by writing square(3) . ( square(3) is the same as writing ( lambda x: x**2)(3) )

Look at another example in which a lambda function takes two arguments and returns the sum of the arguments.

The lambda function takes two arguments x and y and then returns the sum of the arguments. Two values 3 and 2 are passed to the lambda function by writing (3, 2) after the function definition. The first value 3 got assigned to x and the second value 2 got assigned to y .

In the next example, the lambda function created is assigned to a variable sum .

sum = lambda x, y: x + y print(sum(3, 2)) 

Источник

Оцените статью