Introduction: Why Map and Filter are Essential Python Tools
Welcome to the world of Pythonic coding! If you’ve been working with data in Python, you’ve likely spent a lot of time writing for
loops to process lists, tuples, and other iterables. While effective, these loops can sometimes lead to verbose, less readable code.
Enter the dynamic duo of functional programming in Python: the map()
and filter()
functions. These two built-in utilities are not just historical relics; they are fundamental tools for any Python developer looking to write cleaner, faster, and more expressive code.
At their heart, both map()
and filter()
help you perform operations on collections of data without manually managing indices or intermediate lists. They represent a shift from telling the computer how to iterate (imperative style) to telling it what the result should be (declarative style).
This ultimate guide will break down the map()
function, the filter()
function, compare their roles, and show you how to use them most effectively alongside other Python features like list comprehensions and lambda functions. By the end, you’ll be equipped to write truly elegant, high-performance Python code.
The Map Function: Transforming Every Element
The map()
function is Python’s primary tool for transformation. Its job is straightforward: take an input sequence and apply the same operation to every single element, producing a new sequence of results.
How map()
Works
The syntax for map()
is:
map(function, iterable)
def square(x):
return x*x
new_list = [1,2,3,4,5,6.3]
square_list = list(map(square,new_list))
print(square_list)
OUTPUT
[1, 4, 9, 16, 25, 39.69]
#PROBLEM STATEMENT - GET PERCENTAGE FROM THE LIST
prices = [100,200,300,400,500]
def percentage(x):
per = x*0.5
return per
percentagelist = list(map(percentage,prices))
print(percentagelist)
OUTPUT
#percentage
[50.0, 100.0, 150.0, 200.0, 250.0]
#PROBLEM STATEMENT : GET PERCENTAGE FROM THE LIST CONVERT THIS FUNCTION USING lambda function
prices = [100,200,300,400,500]
percentagelist1 = []
percentagelist1 = list(map(lambda x : x*0.5,prices))
#make a first letter capital for each element from the list
names=["john","rob","mike"]
capital_list = list(map(str.capitalize,names))
print(capital_list)
#output
['John', 'Rob', 'Mike']
names=["john","rob","mike"]
capital_list = list(map(str.upper,names))
print(capital_list)
#output
['JOHN', 'ROB', 'MIKE']
Filter
def oddnum(y):
if y % 2==1:
return y
sq = list(filter(oddnum,numbers))
print(sq)
[1, 3, 5, 7, 9]
The filter()
function in Python is a built-in function used for selection or filtering elements from an iterable (like a list, tuple, or set) based on a specified condition.
It essentially acts as a sieve, keeping only the elements for which a provided function returns a “truthy” value (True
).
How filter()
Works
The filter()
function has the following syntax:
filter(function,iterable)
function
(The Predicate): This is the function that tests each element in the iterable. It must accept one argument and is expected to return a boolean value (True or False).- If the function returns True, the element is kept.
- If the function returns False (or a “falsy” value like 0 or None), the element is discarded.
iterable
: This is the sequence (list, tuple, etc.) whose elements you want to filter.
Output
The filter()
function returns a filter object (an iterator). This is a memory-efficient generator that yields the filtered elements one by one. To view the results as a standard list or tuple, you must explicitly convert the filter object using list()
or tuple()
.
Example Usage
1. Filtering with a Named Function
Here, we define a function to check if a number is even and use filter()
to apply this check to a list.
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# 1. Define the predicate function
def is_even(num):
# Returns True if num is even, False otherwise
return num % 2 == 0
# 2. Use filter and convert the result to a list
even_numbers = list(filter(is_even, numbers))
print(even_numbers)
# Output: [2, 4, 6, 8]