Processing Sequences with filter() and map() Functions
In Python, the filter() and map() functions in Python are used to process elements of iterable objects like lists and tuples.
The filter() function selects 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 is a callback function, and the second is the iterable object to be processed.
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]
Lessons in this chapter Β· Recursive and Lambda Functions
- 1. Functions That Call Themselves - Recursive Functions
- 2. Comparing Loop and Recursive Functions
- 3. Enhancing Recursive Function Efficiency with Memoization
- 4. Handling UnboundLocalError in Recursion
- 5. Multiple-choice quiz
- 6. Using Functions and Tuples Together
- 7. Functions within Functions - Callback Functions
- 8. Processing Sequences with filter() and map() Functions
- 9. Multiple-choice quiz
- 10. Creating Concise Anonymous Functions with Lambda
- 11. Calculating Fibonacci Sequence Using Lambda Functions
- 12. Coding Quiz - Extract Elements from List
- 13. Multiple-choice quiz
- 14. Fill-in-the-blank quiz
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
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help