map():
The map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator).
Syntax: map(function,iterable)
- function: The function we want to apply to every element of the iterable.
- iterable: The iterable whose elements we want to process.
Example:
a=[1,2,3,4]
def double(value):
return value*2
result = map(double, a)
for i in result:
print(result)
Output:
2
4
6
8
Can even convert it into list.
Let us try :
a=[1,2,3,4]
def double(value):
return value*2
result = map(double, a)
for i in result:
print(result)
Output:
2
4
6
8
[]
Here in the above code we get an empty list why ?
After the for
loop, when you call list(result)
, it tries to convert the result
(which is a map
object) to a list. However, the map
object has already been exhausted because it was iterated over in the for
loop. Once an iterator has been fully iterated, it doesn’t contain any more items to return. So when list(result)
is called, it returns an empty list []
.
filter():
The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Just like map(), it also takes 2 argument and returns a filter object(which is an iterator).
Syntax: filter (function,iterable)
Here the function defined is basically checking a condition on each and every element in iterable and returning the filtered result.
Example:
def even(n):
return n % 2 == 0
a = [1, 2, 3, 4, 5, 6,7,8]
b = filter(even, a)
for i in b:
print(i)
Output:
2
4
6
8
any() and all():
As the name suggests, both of them takes iterable as arguments . While all checks to see if all the items in an iterable are true , any basically checks if any of the item in the iterable are true.
Both function takes an iterable as an argument and return true or false depending on values in iterable.
Example:
enteries=[1,2,3,4,5]
print(all(enteries))
print(any(enteries))
Output:
True
True
Let’s see what if we put one element in enteries as 0
enteries=[1,0,3,4,5]
print(all(enteries))
print(any(enteries))
Output:
False
True