Python

Important Statements

Functions

Lambda Helpers

Variables

The lambda Function (Anonymous Functions)

Creates a small, single-expression function without a name. Useful for short operations where a full def function is overkill.

lambda arguments: expression

Example:

# A lambda function that adds two numbers
add = lambda a, b: a + b
print(add(5, 3)) # Output: 8

# A lambda function that squares a number
square = lambda x: x * x
print(square(4)) # Output: 16

Small Real-Life Use Case

lambda is often used with functions that take other functions as arguments, like sorted(), map(), and filter().

Example with sorted():

Sorting a list of tuples based on the second element:

data = [('apple', 2), ('banana', 1), ('cherry', 3)]

# Sort the list using a lambda function to specify the key
sorted_data = sorted(data, key=lambda item: item[1])

print(sorted_data) # Output: [('banana', 1), ('apple', 2), ('cherry', 3)]