map(), filter () and reduce() operate on lists. But if we want to use them correctly, we'll have to go through lambda expressions first.
lambda
Lambda expressions are a good way to create disposable functions! Just note that they cannot present return statements as their output is the standard return output.
# Note the syntax
add = lambda x, y: x + y
sum(2, 2) # Returns 4
sum(4, 4) # Returns 8
As you can see, this lambda expression for sum is more or less a function definition, turning sum into a function name.
Now we'll see how they can be used to create arbitrary anonymous functions.
# Define a function creates an anonymous function and returnsoutput
def multiply_by(n):
return lambda x : x * n
# The function that is created multiplies the input by 8
multiply_eight = multiply_by(8)
# The function that is created multiplies the input by 6
multiply_six = multiply_by(6)
multiply_eight(2) # Returns 16 (ie 2 * 8)
multiply_six(2) # Returns 12 (ie 2 * 6)
However, the REAL usefulness of lambda expressions comes when you pair them with map (), filter(), reduce().
map()
Map takes a list of items and applies a function to each item in the list.
# Let's make a map to square all the numbers in a list!
numbers = [1, 2, 3, 4, 5]
# Watch the lambda! We don't need to create a new named function for this!
map(lambda x: x ** 2, numbers) # This creates a map object
# We need to create a list for this!
my_squares = list(map(lambda x: x ** 2, numbers))
print(my_squares) # [1, 4, 9, 16, 25] We did it!
# Let's try one more, to capitalize everything in an input string
phrase = "joao"
new_phrase = list(map(lambda x: x.upper(), sentence))
print(new_phrase)
Output —--------------------
[1, 4, 9, 16, 25]
['J', ' O', 'A', 'O']
filter()
The filter executes a function on each item in a list, creating a new list of items that meet the conditions defined by that function. More specifically, items are added to the new list if the applied function returns True
# Let's filter for numbers that are not greater than 3
numbers = [1, 2, 3, 4, 5]
print(list(filter(lambda x: x > 3, numbers)))
Output —--------------------
[4, 5]
reduce()
The reduce() must be imported before it can be used. reduce() 'combines' items in a list, executing a function on each item in a list.
The function you use to iterate through the list needs to be given two values, the first being the accumulated value and the second being the current item you are iterating through the list.
from functools import reduce
numbers = [1, 2, 3, 4]
# Remember, the first value is thevalue
accumulated #and the second is the current value
# This adds all the values!
print(reduce(lambda x, y: x + y, numbers))
# This multiplies all values!
print(reduce(lambda x, y: x * y, numbers))
# This concatenates strings!
print(reduce(lambda x, y: x + y, ["Joao", "Futi"]))
Output —--------------------
10
24
JoaoFuti
List
comprehension in Python List comprehension in Python is an easy and compact syntax to create a list from a string or other list. It's a very concise way to create a new list by performing an operation on each item in the existing list. Understanding the list is considerably faster than processing a list using the for loop.
This is how list comprehensions are used.
# List comprehensions let you define
# lists the same way mathematicians do!
# You can do this with math
exponent_list = [x ** two for x in range(10)]
# Or using conditionals to filter results!
# Here filter only if the exponents are divisible by 2
filtered_list = [x for x in exponent_list if x % two == 0]
# Or do successive bool tests!
bool_list = [(x % two == 0) for x in exponent_list]
print(exponent_list)
print(filtered_list)
print(bool_list)
Output —--------------------
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 4, 16, 36, 64]
[True, False, True, False, True, False, True, False, True, False]
Basically they are very useful and super stylish.
Here is one of the more complicated list comprehensions!
# This one uses two list comprehensions together
without_primes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
primes = [x for x in range(2, 50) if x not in sem_primos]
print(primes)
Output —--------------------
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
You can also use it with non-numbers!
words = 'The quick brown fox jumps over the lazy dog'.split()
things = [[p.upper(), p.lower(), len(p)] for p in words]
for i in things:
print(i)
Output —--------------------
['A', 'a', 1]
['FAST', 'fast', 6]
[' FOX', 'fox', 6]
['BROWN', 'brown', 6]
['LEAP', 'jump', 4]
['ABOUT', 'about', 5]
['O', 'the' , 1]
['DOG', 'dog', 8]
['LAZY', 'lazy', 10]
Sure, you can use lambda functions to get the same result, but it's less understandable.
words = 'The quick brown fox jumps over the lazy dog'.split()
# Sure you can use lambda functions to get the same result
# But it's less understandable
stuff = map(lambda p: [p.upper(), p.lower(), len(p)], words)
for i in things:
print(i)
Output —--------------------
['A', 'a', 1]
['FAST', 'fast', 6]
[' FOX', 'fox', 6]
['BROWN', 'brown', 6]
['LEAP', 'jump', 4]
['ABOUT', 'about', 5]
['O', 'the' , 1]
['DOG', 'dog', 8]
['LAZY', 'lazy', 10]