Definition of Lambda function :
A lambda function in Python is a small, anonymous function defined using the lambda
keyword. It can have any number of arguments but only one expression. It's often used for short operations or as an argument in functions like map()
, filter()
, or sorted()
.
Syntax:
lambda arguments: expression
Example:
# Define a lambda function to add two numbers
add = lambda x, y: x + y
# Call the lambda function with arguments 3 and 4 and print the result
print(add(3, 4)) # Output: 7
1. Using map()
:
The map()
function applies a function (in this case, a lambda function) to all items in an input list.
Example: Doubling each number in a list
# List of numbers to be doubled
numbers = [1, 2, 3, 4, 5]
# Using map() with a lambda function to double each number in the list
doubled = map(lambda x: x * 2, numbers)
# Convert the map object to a list and print the result
print(list(doubled)) # Output: [2, 4, 6, 8, 10]
2. Using filter()
:
The filter()
function filters items from a list based on a condition defined by a lambda function.
Example: Filtering even numbers from a list
# List of numbers to filter even numbers
numbers = [1, 2, 3, 4, 5, 6]
# Using filter() with a lambda function to keep only even numbers
even_numbers = filter(lambda x: x % 2 == 0, numbers)
# Convert the filter object to a list and print the result
print(list(even_numbers)) # Output: [2, 4, 6]
3. Using sorted()
:
The sorted()
function sorts a list. You can pass a lambda function as a key to customize the sorting logic.
Example: Sorting a list of tuples by the second value
# List of tuples to be sorted by the second element of each tuple
pairs = [(1, 'b'), (2, 'a'), (3, 'c')]
# Sorting the list of tuples by the second element (string) using sorted() and lambda
sorted_pairs = sorted(pairs, key=lambda x: x[1])
# Print the sorted list of tuples
print(sorted_pairs) # Output: [(2, 'a'), (1, 'b'), (3, 'c')]
0 Comments