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).
filter(function, iterable)
For example, the filter()
function can be used to filter even numbers from a given list of numbers as shown below.
# 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.
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.
# 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]
What is the purpose of the filter()
function in Python?
To delete elements that meet a condition
To apply a function to each element to create a new sequence
To create a new sequence consisting of elements for which the given function returns True
To sort the elements of a sequence
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result