Hello everyone, I made a small recap of these super useful list functions in Python: map, filter, find, reduce.
Let’s start defining our array.
Defining our array of objects
For example, we gonna use some fruits and their price and quantity.
fruits = [
{
"name": "Apple",
"units": 3,
"price": 0.25
},
{
"name": "Mango",
"units": 6,
"price": 0.35
},
{
"name": "Banana",
"units": 4,
"price": 0.15
},
]
Map function
Creates a new list from the original one.
In our case, we get a new list of strings to store the summary of our fruit’s info.
def summary_func(fruit: dict) -> str:
fruit_cost: float = fruit["price"] * fruit["units"]
return f'{fruit["units"]} units of {fruit["name"]} costs ${fruit_cost:.2f}'
summary = list(map(summary_func, fruits))
# List of str
print(summary)
"""
[
'3 units of Apple costs $0.75',
'6 units of Mango costs $2.10',
'4 units of Banana costs $0.60'
]
"""
Filter function
Create a new list from the original one when a condition is met.
For us, we get a new list of fruit items with fruits price lower than $0.20.
acceptable_price = 0.2
def only_cheaper_func(fruit: dict) -> bool:
if fruit["price"] < acceptable_price:
return True
else:
return False
only_cheaper = list(filter(only_cheaper_func, fruits))
# List of fruit dict
print(only_cheaper)
"""
[
{
'name': 'Banana',
'units': 4,
'price': 0.15
}
]
"""
Find function
Return the first item found (or None
if not found) in the original list when a condition is met.
An example, we found the mango fruit info.
search = "mango"
find_mango = next((fruit for fruit in fruits if search in fruit["name"].lower()), None)
# One fruit dict, without list
print(find_mango)
"""
{
name: 'Mango',
units: 6,
price: 0.35
}
"""
Reduce function
Returns an accumulated (or reduced) value from the original array.
In our case, we calculated the cost of the fruits and accumulate them to get the total.
def grand_total_func(accumulator: float, fruit: dict) -> float:
fruit_cost: float = fruit["price"] * fruit["units"]
return accumulator + fruit_cost
initial_value = 0
grand_total = functools.reduce(grand_total_func, fruits, initial_value)
# Number value
print(f"Grand Total: ${grand_total:.2f}")
# Grand Total: $3.45
Final thoughts
As you can see these concepts are easy to understand and are super useful in a development day.
I hope this will be useful to you as they are to me in my daily development road.
Also, this is a great book to easily learn python for beginners, check it out if you are interested in learning more about it: https://amzn.to/3m0hYlS.
Here is a JavaScript equivalent for these functions: https://hhsm95.dev/blog/javascript-useful-array-functions-map-filter-find-and-reduce/
Also, this is the full code: https://gitlab.com/-/snippets/2141285
PD. Yeah, I know that we can save up some lines but this is an understanding approach for the people learning Python.