Lambda Functions and Map, Filter, Reduce
⏱ Estimated reading time: 2 min
Lambda Functions and Map, Filter, Reduce in Python
Python provides anonymous functions (lambda) and higher-order functions like map, filter, and reduce to write concise and functional-style code.
1. Lambda Functions
-
Anonymous functions created using the
lambdakeyword. -
Can have any number of arguments but only one expression.
-
Useful for short, simple functions.
Syntax:
Examples:
2. Map Function
-
map(function, iterable)applies a function to every element of an iterable. -
Returns a map object (can be converted to list, tuple, etc.).
Example with lambda:
Example with a regular function:
3. Filter Function
-
filter(function, iterable)selects elements where the function returns True. -
Returns a filter object.
Example with lambda:
Example with a regular function:
4. Reduce Function
-
reduce(function, iterable)applies a function cumulatively to the items of an iterable. -
Returns a single value.
-
Requires importing from
functools.
Example with lambda:
Example with regular function:
5. Key Points
-
Lambda functions are best for small, simple operations.
-
Map transforms each element of a sequence.
-
Filter selects elements based on a condition.
-
Reduce aggregates elements into a single result.
-
Combining these allows concise, functional-style programming in Python.
Register Now
Share this Post
← Back to Tutorials