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.
Anonymous functions created using the lambda keyword.
Can have any number of arguments but only one expression.
Useful for short, simple functions.
Syntax:
Examples:
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:
filter(function, iterable) selects elements where the function returns True.
Returns a filter object.
Example with lambda:
Example with a regular 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:
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.
Take quizzes related to this topic and see where you stand!
Start Quiz Now