Unlock the Power of Lambda Functions in Python
What is a Lambda Function?
Imagine having a function without a name – that’s what a lambda function is in Python! It’s a special type of function that allows you to execute a block of code without declaring a separate function. But before we dive deeper, make sure you have a solid understanding of Python functions.
Declaring a Lambda Function
To create a lambda function, you use the lambda
keyword instead of def
. The syntax is simple:
lambda argument(s): expression
Here, argument(s)
represents any value passed to the lambda function, and expression
is the code that gets executed and returned.
A Simple Lambda Function Example
Let’s create a lambda function that prints ‘Hello World’ and assign it to a variable named greet
. To execute the lambda function, we simply call it:
greet = lambda: print('Hello World')
When we call greet()
, the print()
statement inside the lambda function is executed, printing ‘Hello World’ to the console.
Lambda Functions with Arguments
Just like regular functions, lambda functions can also accept arguments. Let’s create a lambda function that takes a name
argument and prints a personalized greeting:
greet_user = lambda name: print(f'Hello, {name}!')
When we call greet_user('Delilah')
, the lambda function executes the print()
statement with the name
argument, printing ‘Hello, Delilah!’ to the console.
Working with Filter and Map Functions
Filtering Data with filter()
The filter()
function in Python takes a function and an iterable (like lists, tuples, or strings) as arguments. It returns a new list containing only the items for which the function evaluates to True
. For example, let’s use filter()
to extract only the even numbers from a list:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
Transforming Data with map()
The map()
function takes a function and an iterable as arguments, returning a new list containing the results of applying the function to each item. Let’s use map()
to double all the items in a list:
numbers = [1, 2, 3, 4, 5, 6]
doubled_numbers = list(map(lambda x: x * 2, numbers))
Frequently Asked Questions
…and more!