0% found this document useful (0 votes)
2 views3 pages

Map, Filter, Reduce

A lambda function is an anonymous function that can take multiple arguments but only has one expression. It is commonly used with functions like map, filter, and reduce to transform, filter, or accumulate values from lists. Examples demonstrate how to use lambda functions with these higher-order functions to achieve various outcomes.

Uploaded by

vikkee493
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Map, Filter, Reduce

A lambda function is an anonymous function that can take multiple arguments but only has one expression. It is commonly used with functions like map, filter, and reduce to transform, filter, or accumulate values from lists. Examples demonstrate how to use lambda functions with these higher-order functions to achieve various outcomes.

Uploaded by

vikkee493
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Python Lambda

A lambda function is a small anonymous function. (a function without a name.)

A lambda function can take any number of arguments, but can only have one
expression.

Syntax
lambda arguments : expression

The expression is executed and the result is returned:

Example

Multiply argument a with argument b and return the result:

x = lambda a, b : a * b

print(x(5, 6))

Example

Summarize argument a, b, and c and return the result:

x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

🔹 1. map(): Apply a function to each item in a list.


Use: When you want to change or transform every item in a list.

Syntax: map(function, iterable)

Example:

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

🔹 2. filter(): Filter items based on a condition.


Use: When you want to select items from a list based on some rule.

Syntax: filter(function, iterable)

Example:

numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # Output: [2, 4, 6]

🔹 3. reduce(): Apply a function to accumulate values.


Use: When you want to combine all items into a single value (e.g., sum, product).

Import it first: from functools import reduce

Syntax: reduce(function, iterable)

Example:

from functools import reduce

numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24 (1*2*3*4)

🔸 Summary Table:
Function Purpose Output Example

map() Transform all items [1, 4, 9, 16]


filter() Select items based on [2, 4, 6]
condition

reduce() Combine all items to one 24


value

You might also like