python


Python provides powerful tools for functional programming, allowing you to write concise and efficient code. Four commonly used features are: ✔ Lambda functions (anonymous functions) ✔ map() – Apply a function to all items ✔ filter() – Filter items based on a condition ✔ reduce() – Apply a function cumulatively to reduce a list to a single value

1. Lambda Functions

A lambda function is an anonymous (nameless) function defined using the `lambda` keyword.

Syntax:


lambda arguments: expression


Example:


square = lambda x: x * x
print(square(5))  # Output: 25


✔ One-liner functions
✔ Used for short operations



2. map() Function

`map()` applies a function to each element in an iterable (list, tuple, etc.) and returns a map object (which can be converted to a list).

Syntax:


map(function, iterable)


Example:


numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x2, numbers))
print(squared)  # [1, 4, 9, 16]




3. filter() Function

`filter()` filters elements from an iterable based on a condition (True/False).

Syntax:


filter(function, iterable)


Example:


numbers = [10, 15, 20, 25, 30]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # [10, 20, 30]




4. reduce() Function

`reduce()` is used to apply a function cumulatively to items in an iterable. It reduces the iterable to a single value.

Syntax:


reduce(function, iterable)


Import from `functools`:


from functools import reduce

numbers = [1, 2, 3, 4, 5]
sum_all = reduce(lambda x, y: x + y, numbers)
print(sum_all)  # Output: 15




Comparison Table

| Function     | Purpose                                      |
|  | -- |
| lambda   | Create anonymous functions                   |
| map()    | Apply a function to each element             |
| filter() | Select elements based on a condition         |
| reduce() | Reduce elements to a single cumulative value |



When to Use?

* Use lambda when the function is small and used only once.
* Use map for transformations.
* Use filter for conditions.
* Use reduce for cumulative calculations like sum or product.



Example Combining All


from functools import reduce

numbers = [1, 2, 3, 4, 5]

# Square all numbers
squares = list(map(lambda x: x2, numbers))

# Filter even squares
even_squares = list(filter(lambda x: x % 2 == 0, squares))

# Sum of even squares
sum_even_squares = reduce(lambda x, y: x + y, even_squares)

print(squares)            # [1, 4, 9, 16, 25]
print(even_squares)       # [4, 16]
print(sum_even_squares)   # 20




Summary

* lambda → Small anonymous functions
* map() → Apply function to all elements
* filter() → Keep elements that meet a condition
* reduce() → Combine elements into a single value