Anonymous functions, also known as lambda functions, are a type of function in Python that do not have a name. They are typically used when you need to pass a small function as an argument to another function. Lambda functions are defined using the keyword “lambda” followed by the function’s input arguments and the function body. They can take any number of arguments but can only have one expression in the function body.
Lambda functions are often used with functional programming constructs like map(), filter() and reduce(). They can also be assigned to a variable, just like a regular function. However, since lambda functions do not have a name, they cannot be called directly. Instead, they are typically used as an argument to another function or used to create a new function.
Lambda functions can be useful when you need a simple function that will only be used once, and you do not want to define a named function. They are also useful when you need to create a function that takes another function as an argument. Lambda functions are a powerful feature of Python that can help make your code more concise and expressive.
The syntax for defining an anonymous function (lambda function) in Python is as follows:
lambda arguments: expression
Here, arguments
refers to the input arguments for the function, separated by commas. These are the arguments that will be passed to the function when it is called. The expression
is a single expression that will be evaluated when the function is called. The value of this expression will be the return value of the function.
For example, the following lambda function takes two arguments and returns their sum:
sum = lambda x, y: x + y
This lambda function can be called like any other function:
result = sum(3, 5)
print(result) # Output: 8
Note that lambda functions can only contain a single expression. If you need to do more complex operations, you should define a regular named function instead.
Lambda functions, also known as anonymous functions, are often used in Python programming for several purposes. Here are a few examples of how lambda functions can be used in Python:
map()
, filter()
, and reduce()
. These functions take a lambda function as the first argument and perform operations on the input data based on the lambda function’s logic. For example:# Using lambda function with map() to square each element in a list
lst = [1, 2, 3, 4, 5]
squared_lst = list(map(lambda x: x**2, lst))
print(squared_lst) # Output: [1, 4, 9, 16, 25]
# Using lambda function to sort a list of tuples based on the second element of each tuple
lst = [(2, "b"), (1, "a"), (4, "d"), (3, "c")]
sorted_lst = sorted(lst, key=lambda x: x[1])
print(sorted_lst) # Output: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
# Using lambda function to create a custom function that checks if a number is even
is_even = lambda x: x % 2 == 0
print(is_even(4)) # Output: True
# Using lambda function to create a closure that remembers the value of the variable 'a'
def outer_func():
a = 5
return lambda x: x + a
inner_func = outer_func()
print(inner_func(3)) # Output: 8
These are just a few examples of how lambda functions can be used in Python programming. Lambda functions are a powerful tool that can help you write more concise and expressive code.
# Using lambda function to create an event handler for a button in a GUI application
button = tkinter.Button(root, text='Click me')
button.config(command=lambda: print('Button clicked!'))
# Using lambda function to sort a list of dictionaries based on a specific key
data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 20}, {'name': 'Charlie', 'age': 30}]
sorted_data = sorted(data, key=lambda x: x['age'])
print(sorted_data) # Output: [{'name': 'Bob', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}]
# Using lambda function to pass a custom function as an argument to the 'sorted()' function
lst = [(2, "b"), (1, "a"), (4, "d"), (3, "c")]
sorted_lst = sorted(lst, key=lambda x: x[1])
print(sorted_lst) # Output: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
# Using lambda function with ternary operator to simplify a conditional statement
is_even = lambda x: True if x % 2 == 0 else False
print(is_even(4)) # Output: True
These are just a few more examples of how lambda functions can be used in Python programming. Lambda functions are a versatile tool that can help you write more concise and readable code.
# Using lambda function to create a closure with a default value for 'a'
def outer_func(a):
return lambda x: x + a
inner_func = outer_func(5)
print(inner_func(3)) # Output: 8
# Using lambda function to create a generator that generates Fibonacci numbers
fibonacci = lambda n: (0, 1) if n == 0 else (lambda x, y: (y, x + y))(fibonacci(n-1))
print(fibonacci(0)) # Output: 0
print(fibonacci(1)) # Output: 1
print(fibonacci(2)) # Output: 1
print(fibonacci(3)) # Output: 2
print(fibonacci(4)) # Output: 3
print(fibonacci(5)) # Output: 5
map()
function. For example:# Using lambda function with 'map()' to add corresponding elements of two lists
lst1 = [1, 2, 3]
lst2 = [4, 5, 6]
result = list(map(lambda x, y: x + y, lst1, lst2))
print(result) # Output: [5, 7, 9]
# Using lambda function to create a decorator that times a function's execution
import time
def timing_decorator(func):
return lambda *args, **kwargs: (time_start := time.time(), result := func(*args, **kwargs), time.time() - time_start)[1:]
@timing_decorator
def my_function(x, y):
time.sleep(1)
return x + y
print(my_function(2, 3)) # Output: (5,)
These are just a few more examples of how lambda functions can be used in Python programming. Lambda functions are a versatile and powerful tool that can help you write more concise and expressive code.
filter()
function. For example:# Using lambda function with 'filter()' to filter a list of numbers
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = list(filter(lambda x: x % 2 == 0, lst))
print(result) # Output: [2, 4, 6, 8]
reduce()
function. For example:# Using lambda function with ‘reduce()’ to compute the intersection of two sets
from functools import reduce
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = reduce(lambda x, y: x & y, [set1, set2])
print(result) # Output: {3, 4}
sorted()
function. For example:# Using lambda function with 'sorted()' to sort a list of tuples based on multiple criteria
lst = [('John', 25), ('Bob', 30), ('Alice', 20), ('Charlie', 25)]
result = sorted(lst, key=lambda x: (x[1], x[0]))
print(result) # Output: [('Alice', 20), ('Charlie', 25), ('John', 25), ('Bob', 30)]
# Using lambda function to create a key function for sorting a Pandas DataFrame by a specific column
import pandas as pd
data = {'name': ['Alice', 'Bob', 'Charlie', 'David'], 'age': [25, 30, 20, 35]}
df = pd.DataFrame(data)
result = df.sort_values(by=lambda x: x['age'])
print(result) # Output: name age
2 Charlie 20
0 Alice 25
1 Bob 30
3 David 35
# Using lambda function to create an anonymous function for a Tkinter button click event
import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text='Click me', command=lambda: print('Button clicked'))
button.pack()
root.mainloop()
# Using lambda function to create a dynamic SQL query for a database
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
engine = create_engine('sqlite:///example.db', echo=True)
metadata = MetaData()
users = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String),
Column('age', Integer),
Column('email', String),
)
result = engine.execute(users.select().where(lambda x: x.age > 30))
for row in result:
print(row)
# Using lambda function to create a complex data transformation in PySpark
from pyspark.sql.functions import udf
from pyspark.sql.types import IntegerType
data = [('Alice', 25), ('Bob', 30), ('Charlie', 20), ('David', 35)]
df = spark.createDataFrame(data, ['name', 'age'])
my_udf = udf(lambda x: x * 2 if x > 30 else x, IntegerType())
result = df.select('name', my_udf('age').alias('age'))
result.show()
To create custom comparison functions: Lambda functions can be used to create custom comparison functions for sorting and searching algorithms. For example:
# Using lambda function to create a custom comparison function for a binary search algorithm def binary_search(lst, key, comp=lambda x, y: x < y): low, high = 0, len(lst) – 1 while low <= high: mid = (low + high) // 2 if comp(lst[mid], key): low = mid + 1 elif comp(key, lst[mid]): high = mid – 1 else: return mid return -1 lst = [1, 3, 5, 7, 9] key = 5 result = binary_search(lst, key, comp=lambda x, y: x > y) print(result) # Output: 2 These are just a few more examples of how lambda functions can be used in Python programming. Lambda functions can be used in almost any situation where a function is required, and their simplicity and conciseness make them a valuable tool for many programming tasks.
here’s a multi-choice quiz about lambda functions in Python:
Answer: c
def my_function():
b. lambda x: x + 1
c. def my_function(x):
Answer: b
Answer: a
Answer: a
Answer: a
lambda x: x + x
b. lambda x, y: x - y
c. lambda x, y: x + y
Answer: c
x = lambda a: a * 2
print(x(5))
a. 10 b. 5 c. 25
Answer: a
my_list = [1, 2, 3, 4, 5]
new_list = list(map(lambda x: x * 2, my_list))
print(new_list)
a. [1, 2, 3, 4, 5]
b. [2, 4, 6, 8, 10]
c. [1, 4, 9, 16, 25]
Answer: b
my_list = [1, 2, 3, 4, 5]
new_list = list(filter(lambda x: x % 2 == 0, my_list))
print(new_list)
a. [1, 3, 5]
b. [2, 4]
c. [1, 2, 3, 4, 5]
Answer: b
print()
b. sorted()
c. int()
Answer: b
def my_function(n):
return lambda a: a * n
my_doubler = my_function(2)
print(my_doubler(5))
a. 10 b. 5 c. 25
Answer: a