Skip to main content
Practice

Processing Sequences with filter() and map() Functions

The filter() and map() functions in Python are used to process elements of iterable objects like lists and tuples.

The filter() function is used to filter elements that satisfy a given condition, and the map() function applies a specified function to each element, creating a new sequence.


Using the filter() Function

The filter() function generates a new sequence composed of elements for which the given function returns True.

The first argument of the filter function is a callback function, and the second argument is the iterable object (sequence).

Usage of filter function
filter(function, iterable)

For example, the filter() function can be used to filter even numbers from a given list of numbers as shown below.

Example of using filter() function
# Callback function to filter even numbers
def is_even(number):
return number % 2 == 0

# List of numbers
numbers = [1, 2, 3, 4, 5, 6]

# Using filter() function
even_numbers = filter(is_even, numbers)

even_list = list(even_numbers)
print(even_list)
# [2, 4, 6]

Using the map() Function

The map() function takes an iterable object, applies a specified function to each element, and creates a new map object containing the results.

It can be used with any iterable object like lists, tuples, or strings, and the new map object can be converted into other data types like lists or tuples.

Usage of map function
map(function, iterable)

This function is commonly used in data transformation tasks, making it useful for processing all elements of an iterable object in bulk.

Example of using map() function
# Callback function to square numbers
numbers = [1, 2, 3, 4, 5, 6]

def square(number):
return number * number

# Using map() function
squared_numbers = map(square, numbers)

print(list(squared_numbers))
# [1, 4, 9, 16, 25, 36]

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.