The Map() and Filter() Function

The map() Function

The map() function in Python is used to apply a specified function to all items in an input iterable (such as a list, tuple, or string) and return an iterator of the results.

The basic syntax of the map() function is as follows:

map(function, iterable, ...)

Example:

numbers = [1, 2, 3, 4]

# Using map to square each element in the list
squared_numbers = map(lambda x: x**2, numbers)

# Converting the iterator to a list
result_list = list(squared_numbers)

print(result_list)
[1, 4, 9, 16]

The filter() Function

The filter() function in Python is used to construct an iterator from elements of an iterable for which a function returns true. In other words, it filters the elements of an iterable based on a given function.

The basic syntax of the filter() function is as follows:

filter(function, iterable)

Example:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using filter to keep only even numbers
filtered_numbers = filter(lambda x: x % 2 == 0, numbers)

# Converting the iterator to a list
result_list = list(filtered_numbers)

print(result_list)
[2, 4, 6, 8, 10]

In this example, the filter() function applies the lambda function (lambda x: x % 2 == 0) to each element in the numbers list. The lambda function checks if the number is even, and only those numbers for which the function returns True are included in the result.

Powered by Forestry.md