Python Map and Filter
Python map function
The Python map()
function applies a function to a set of elements in an iterable, such as a list. Here’s an example of how to use it:
def multiply_by_two(x):
return x * 2
numbers = [1, 2, 3, 4]
result = map(multiply_by_two, numbers)
print(list(result))
The output of this code would be [2, 4, 6, 8]
.
The map()
function applies the multiply_by_two()
function to each element in the numbers
list, and returns a map object with the results. To see the results, you can convert the map object to a list, as shown in the print()
statement. You can also use the map()
function with multiple iterables. For example:
def multiply(x, y):
return x * y
numbers1 = [1, 2, 3, 4]
numbers2 = [2, 3, 4, 5]
result = map(multiply, numbers1, numbers2)
print(list(result))
This would output [2, 6, 12, 20]
. The map()
function applies the multiply()
function to each pair of elements (one from numbers1
and one from numbers2
), and returns a map object with the results.
Python filter function
The filter()
function in Python is used to filter a sequence of data, such as a list, by applying a function to each element in the list and only keeping the elements for which the function returns a True value. Here’s an example of how to use it:
def is_even(num):
return num % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(is_even, numbers)
print(even_numbers) # prints [2, 4, 6, 8, 10]
The filter()
function takes two arguments: the function and the iterable (such as a list). It returns an iterator that produces the elements of the iterable for which the function returns a True value.
You can also use the filter()
function with a lambda function (an anonymous function) instead of a named function like is_even()
:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(even_numbers) # prints [2, 4, 6, 8, 10]
You can also use the filter()
function with other iterables, such as strings:
vowels = 'aeiou'
def is_vowel(char):
return char in vowels
sentence = 'This is a sentence.'
vowels_in_sentence = filter(is_vowel, sentence)
print(vowels_in_sentence) # prints 'i i a ee'