map(), filter() and reduce()
Map function takes in a function and an iterable as arguments and applies the function on each value of iterable and returns themes.
Syntax:
map(function, iterable)
Traditional way
Python3
nums = [ 1 , 2 , 3 , 4 ] def double(n): return 2 * n twice = [] for val in nums: twice.append(double(val)) print (twice) |
One Liner
Python3
nums = [ 1 , 2 , 3 , 4 ] def double(n): return 2 * n twice = list ( map (double, nums)) print (twice) #Output - [2, 4, 6, 8] |
Often, lambda functions are used in the map():
Python3
nums = [ 1 , 2 , 3 , 4 ] twice = list ( map ( lambda x: 2 * x, nums)) print (twice) #Output - [2, 4, 6, 8] |
Filter function also takes in a function (which may also be a lambda function) and an iterable and returns an iterator to an iterable object which contains values filtered according to the logic of the passed function.
Syntax:
filter(function, iterable)
Examples
Python3
nums = [ 1 , 20 , 3 , 5 , 15 ] five_multiples = list ( filter ( lambda x: x % 5 = = 0 , nums)) print (five_multiples) # Output [20, 5, 15] |
Reduce function takes in an iterable and a function (which may also be a lambda function) and returns a single value as a result thus, in a way reducing the entire iterable into a single value according to the logic of the passed function.
Syntax:
reduce(function, iterable)
Python3
# sum of all numbers in a list from functools import reduce nums = [ 2 , 3 , 5 , 15 ] sum = reduce ( lambda x, y: x + y, nums) print ( sum ) # Output 25 |
Python3
# max of all numbers in a list from functools import reduce nums = [ 2 , 3 , 5 , 15 ] max = reduce ( lambda x, y: x if x > = y else y, nums) print ( max ) # Output 15 |
We can see that reduce takes two values at a time and compute their result according to the function definition.
E.g. to calculate the max value, the first 2 and 3 will be compared and the maximum of the two i.e. 3 is returned which is then compared with the subsequent number 5, and so on. Reduce function also works when the iterable contains only one element but will give an error when it is empty.
10 Useful Python One Liners That Developers Must Know
Python is known for its easy-to-code and intuitive syntax. And one-liners are like the cherry on the cake which makes Python a more beautiful and beloved programming language. There are numerous features in Python Language and one of its most loved features is its one-liners. Writing Code in Python is already easy compared to other programming languages and using the one-liners makes it more easier and cool. Now let’s see what are these Python one-liners.