Lambda Functions
In Python, a lambda function is an anonymous (unnamed) function defined in a single line using the lambda
keyword. They are useful for short operations, such as transforming data or filtering elements, especially when using higher-order functions like map()
, filter()
, and sorted()
.
Characteristics of lambda functions:
Section titled “Characteristics of lambda functions:”-
Anonymous: They have no defined name.
-
Simple syntax: They are defined with
lambda
followed by arguments,:
and an expression. -
Single expression: They can only contain a single expression for the result.
-
Use with higher-order functions: They are common with
map()
,filter()
andsorted()
.
Implementation
Section titled “Implementation”Square of a number.
square = lambda x: x**2print(square(5))
Output:
25
Function to check if a number is even:
is_even = lambda x: x % 2 == 0print(is_even(4))print(is_even(7))
Output:
TrueFalse
Use with map().
Section titled “Use with map().”numbers = [1, 2, 3, 4, 5]squares = list(map(lambda x: x**2, numbers))print(squares)
Output:
[1, 4, 9, 16, 25]
Use with filter().
Section titled “Use with filter().”numbers = [1, 2, 3, 4, 5, 6]even_numbers = list(filter(lambda x: x % 2 == 0, numbers))print(even_numbers)
Output:
[2, 4, 6]
Use with sorted().
Section titled “Use with sorted().”words = ['banana', 'pear', 'apple', 'grape']sorted_words = sorted(words, key=lambda x: len(x))print(sorted_words)
Output:
['grape', 'pear', 'apple', 'banana']