Python is renowned for its readability, flexibility, and simplicity, making it a favourite among programmers. Among its powerful features are the filter(), map(), and lambda() functions. These tools allow for cleaner, more efficient code by enabling functional programming constructs within Python. In this article, we’ll dive deep into these functions, exploring their syntax, usage, and practical examples.
Table of Contents
The Filter Function
The filter() function is used to filter items in an iterable (like lists or tuples) based on a condition or function. It returns only the elements for which the function evaluates to True.
Syntax:
filter(function, iterable)
Python- function: A function that returns a boolean (True or False) for each element.
- iterable: The iterable to be filtered (list, tuple, set, etc.).
The result is a filter object (an iterator), which you can convert to a list, tuple, or set.
Example 1
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Filter out even numbers
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
# Output:
[2, 4, 6, 8, 10]
PythonEquivalent
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers= []
for n in numbers:
if n%2==0:
even_numbers.append(n)
print(even_numbers)
# Output:
[2, 4, 6, 8, 10]
PythonIn this example, the lambda function (lambda x: x % 2 == 0) is applied to each element of the list, and only those that are divisible by 2 (even numbers) are returned.
Example 2
ages = [5, 12, 17, 18, 24, 32]
def myFunc(x):
if x < 18:
return False
else:
return True
adults = filter(myFunc, ages)
for x in adults:
print(x)
#output
18
24
32
PythonExample 3
# Define a function to check if a string has more than 5 characters
def longer_than_five(s):
return len(s) > 5
words = ["apple", "banana", "pear", "watermelon", "grape"]
# Use filter with the longer_than_five function
long_words = filter(longer_than_five, words)
print(list(long_words)) # Output: ['banana', 'watermelon']
PythonExample 4
# Define a function to check if a number is even
def is_even(num):
return num % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use filter with the is_even function
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) # Output: [2, 4, 6, 8, 10]
PythonExample 5
# Define a function to check if a number is positive
def is_positive(n):
return n > 0
numbers = [-10, -5, 0, 5, 10, 15]
# Use filter with the is_positive function
positive_numbers = filter(is_positive, numbers)
print(list(positive_numbers)) # Output: [5, 10, 15]
PythonExample 6
# Define a function to check if a person is an adult
def is_adult(person):
return person['age'] >= 18
people = [
{'name': 'John', 'age': 17},
{'name': 'Jane', 'age': 22},
{'name': 'Tom', 'age': 16},
{'name': 'Lucy', 'age': 19}
]
# Use filter with the is_adult function
adults = filter(is_adult, people)
print(list(adults))
# Output: [{'name': 'Jane', 'age': 22}, {'name': 'Lucy', 'age': 19}]
PythonThe Map Function
The map() function applies a given function to all the items in an iterable and returns a new iterable (a map object) with the results.
Syntax
map(function, iterable)
Python- function: A function to apply to each element.
- iterable: The iterable (like a list, tuple, etc.).
Just like filter(), the result is a map object, which can be converted into a list, tuple, or set.
Example 1
numbers = [1, 2, 3, 4, 5]
# Square each number
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers))
# Output:
[1, 4, 9, 16, 25]
PythonHere, the lambda function squares each element in the numbers list, producing a new list of squared values.
Example 2
def myfunc(a):
return len(a)
x = map(myfunc, ('apple', 'banana', 'cherry'))
#convert the map into a list, for readability:
print(list(x))
#output
[5, 6, 6]
PythonThe Lambda Function
lambda functions are anonymous, one-liner functions defined using the lambda keyword. They are used primarily for short, throwaway functions or as arguments in higher-order functions like filter() and map().
Syntax
lambda arguments: expression
Python- arguments: Comma-separated parameters.
- expression: The single expression to be evaluated and returned.
lambda functions are commonly used with filter() and map() but can also be assigned to variables.
Use lambda functions when an anonymous function is required for a short period of time.
Example 1
# A lambda function that adds two numbers
add = lambda x, y: x + y
print(add(3, 5))
# Output: 8
PythonThis example shows a simple lambda function that takes two arguments and returns their sum.
Non Equivalent Lambda
def add(x,y):
return x+y
PythonExample 2
The power of lambda is better shown when you use it as an anonymous function inside another function.
Say you have a function definition that takes one argument, and that argument will be multiplied by an unknown number:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mydoubler(11))
#Output
22
33
PythonPerformance Considerations
While filter(), map(), and lambda() functions offer clean, functional-style solutions, there are performance trade-offs:
- Readability: Overusing lambda in deeply nested expressions may make the code harder to read. Named functions are often more descriptive.
- Memory Efficiency: Both filter() and map() return iterators, which are more memory-efficient than lists. However, wrapping these objects in list() or tuple() may negate this benefit.
Practice
Example 1
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Filter even numbers and square them
even_squares = map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers))
print(list(even_squares)) # Output: [4, 16, 36, 64, 100]
PythonExample 2
words = ["apple", "banana", "cherry", "date", "fig", "grape"]
result = list(map(lambda s: s.upper(), filter(lambda s: 'a' in s, words)))
print(result) # Output: ['APPLE', 'BANANA', 'DATE', 'GRAPE']
PythonExample 3
floats = [7.1, 12.6, 3.8, 15.4, 9.7]
result = list(map(lambda x: round(x), filter(lambda x: x >= 10, floats)))
print(result) # Output: [13, 15]
PythonExample 4
strings = ["cat", "elephant", "dog", "giraffe", "mouse"]
result = list(map(lambda s: len(s), filter(lambda s: len(s) >= 5, strings)))
print(result) # Output: [8, 7, 5]
PythonExample 5
from datetime import datetime
date_strings = ["2021-05-15", "2023-08-01", "2024-01-10", "2022-12-31"]
result = list(map(lambda d: datetime.strptime(d, "%Y-%m-%d"), filter(lambda d: datetime.strptime(d, "%Y-%m-%d").year >= 2023, date_strings)))
print(result) # Output: [datetime.datetime(2023, 8, 1, 0, 0), datetime.datetime(2024, 1, 10, 0, 0)]
PythonReduce
reduce is a function in Python’s functools module used to apply a function cumulatively to the items of an iterable, reducing it to a single value. Essentially, it performs a rolling computation.
from functools import reduce
result = reduce(function, iterable[, initializer])
Python- function: A function that takes two arguments and performs an operation.
- iterable: An iterable like a list or tuple whose elements are to be reduced.
- initializer (optional): An initial value that is used as the first argument in the first call of the function.
Example : Sum of a list
from functools import reduce
#Example 1
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, numbers)
print(result) # Output: 15
#Example 2
result = reduce(lambda x, y: x * y, numbers)
print(result) # Output:120
#Example 3
numbers = [1, 5, 3, 9, 2]
result = reduce(lambda x, y: x if x > y else y, numbers)
print(result) # Output: 9
PythonExplanation for example 1
Step-by-Step Execution:
First Iteration:
- x = 1 (the first element)
- y = 2 (the second element)
- lambda(1, 2) → 1 + 2 = 3
- So, the result of this step is 3.
Second Iteration:
- x = 3 (result from the previous step)
- y = 3 (the third element)
- lambda(3, 3) → 3 + 3 = 6
- So, the result of this step is 6.
Third Iteration:
- x = 6 (result from the previous step)
- y = 4 (the fourth element)
- lambda(6, 4) → 6 + 4 = 10
- So, the result of this step is 10.
Final Result: After all iterations, the final result is 10, which is returned.
Conclusion
The filter()
, map()
, and lambda()
functions are powerful tools in Python’s functional programming arsenal. They allow for concise, readable, and efficient code, especially when dealing with data transformation and filtering tasks. Understanding when and how to use them effectively can significantly improve your coding productivity and the elegance of your solutions.
1 thought on “Understanding lambda(), map(), and filter() in Python”