Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

lambda

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

lambda

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

A lambda function in Python is a small anonymous function defined using the lambda

keyword.
Lambda functions can have any number of arguments but only one expression.
They are often used as a concise way to create simple functions without needing to
define a separate function using the def keyword.

::Syntax::
lambda arguments : expression

Here are five easy examples of lambda functions in Python:

Adding two numbers:

add = lambda x, y: x + y
print(add(3, 5)) # Output: 8

Multiplying two numbers:

multiply = lambda x, y: x * y
print(multiply(3, 5)) # Output: 15

Squaring a number:

square = lambda x: x ** 2
print(square(3)) # Output: 9

Checking if a number is even:

is_even = lambda x: x % 2 == 0
print(is_even(4)) # Output: True
print(is_even(3)) # Output: False

Reversing a string:

reverse_str = lambda s: s[::-1]


print(reverse_str("hello")) # Output: "olleh"
In each example:

The lambda keyword is used to define an anonymous function.


The arguments are specified before the colon (:).
The expression to be evaluated is specified after the colon.
Lambda functions are typically used for simple operations where defining a full
function using def would be overly verbose.

----------------------------difference with the normal function-----------------


compare a normal function with a lambda function for a simple task, such as
squaring a number.

Using a Normal Function:

def square(x):
return x ** 2

print(square(3)) # Output: 9
Using a Lambda Function:

square_lambda = lambda x: x ** 2
print(square_lambda(3)) # Output: 9
In both cases, we're defining a function to square a number (x ** 2). Here's the
difference:

The normal function (square) is defined using the def keyword and has a name
(square).
The lambda function (square_lambda) is defined using the lambda keyword and doesn't
have a name (hence, it's anonymous).
Both functions behave the same way when called with the same arguments.
In this example, the lambda function is more concise, but the trade-off is that it
lacks a name,
making it less readable for more complex operations or when the logic inside the
function becomes longer.
However, for simple operations like this, lambda functions can be quite handy and
reduce code verbosity.

1. less memory-- coz it will not store in heap memory


2. less timecomplexity--- one line function

You might also like