Python Higher-Order Functions

Map

def double(x): 
return x * 2
L1 = [3, 1, 4, 22, 45, 1, 245, 6, 34, 4, 8, 14]
L2 = list(map(double, L1)) print("Doubled Numbers: {}".format(L2))
# [6, 2, 8, 44, 90, 2, 490, 12, 68, 8, 16, 28]
L1 = [3, 1, 4, 22, 45, 1, 245, 6, 34, 4, 8, 14] 
L2 = list(map( (lambda x : x * 2) , L1)) print(L2)
def greet(person): 
print("Hello, {}!".format(person['name']))
people = [ { 'name' : 'John Doe', 'age' : 20}, { 'name' : 'Mike Will', 'age' : 10}, { 'name' : 'Jane Hill', 'age' : 18}, { 'name' : 'Alan Smith', 'age' : 16}, { 'name' : 'Chimuka Chinene', 'age' : 18}, ] list(map(greet, people ))
""" Prints : Hello, John Doe! ... Hello, Chimuka Chinene! """

Reduce

from functools import reduce def addDoubles(a, b): 
return a + (b * 2)
L1 = [3, 1, 4, 22, 45, 1, 245, 6, 34, 4, 8, 14]
doubleSum = reduce(addDoubles, L1, 0)
print(doubleSum) # 774
from functools import reduce L1 = [3, 1, 4, 22, 45, 1, 245, 6, 34, 4, 8, 14] 
doubleSum = reduce( (lambda a,b : a + b * 2) , L1, 0) print(doubleSum) # 774
from functools import reduce L1 = [3, 1, 4, 22, 45, 1, 245, 6, 34, 4, 8, 14] 
sum = reduce( (lambda a,b : a + b * 2) , L1, 1000) # 1000 as initial print(sum) # 1774

Filter

def legal(person): 
return person['age'] >= 18
people = [ { 'name' : 'John Doe', 'age' : 20}, { 'name' : 'Mike Will', 'age' : 10}, { 'name' : 'Jane Hill', 'age' : 18}, { 'name' : 'Alan Smith', 'age' : 16}, { 'name' : 'Chimuka Chinene', 'age' : 18}, ] legal_people = list(filter(legal, people))
print(legal_people)
""" Prints [{'name': 'John Doe', 'age': 20}, {'name': 'Jane Hill', 'age': 18}, #{'name': 'Chimuka Chinene', 'age': 18}] """
people = [ { 'name' : 'John Doe', 'age' : 20}, { 'name' : 'Mike Will', 'age' : 10}, { 'name' : 'Jane Hill', 'age' : 18}, { 'name' : 'Alan Smith', 'age' : 16}, { 'name' : 'Chimuka Chinene', 'age' : 18}, ] legal_people = list(filter( (lambda person : person['age'] >= 18) , people)) print(legal_people) 
""" Prints [{'name': 'John Doe', 'age': 20}, {'name': 'Jane Hill', 'age': 18}, #{'name': 'Chimuka Chinene', 'age': 18}] """

Conclusion

--

--

--

Full-stack software developer. #WebDev #Programming

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Getting Started with PySpark

Dynamic Programming in Go

Amasa Racing Team on REVV Racing: Reward Distribution Week 6, 10–16 January 2022

Composer for BallerinaLang : Ballerina Composer

Library GoogleDrivePy

Untold stories about programming: My journey so far…

Start building your IoT application with IoT Hub (cont.)

The Logical Programming Paradigm

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kelvin

Kelvin

Full-stack software developer. #WebDev #Programming

More from Medium

Python : Conditionals

Using python poetry with .pypirc

SciPy-Tutorial

Lambda in Python