PedroGeoGISdev
  • Home
  • Linux OS
    • Linux: concepts
    • Linux: basic concepts
    • Linux: Bash
    • Linux: su and sudo
    • Linux: pipes
    • Linux: File System
    • Linux: Virtual Machines

    • Linux: distros
    • Linux Distros: Ubuntu
    • Linux Distros: Mint
    • Linux Distros: Debian
    • Linux Distros: openSuse
    • Linux Distros: Manjaro
    • Linux Distros: Red Hat Enterprise

    • Linux: laboratories
    • Linux Lab#LI01-1: Choose Linux
    • Linux Lab#LI01-2: Install at least three distributions
    • Linux Lab#LI01-3: Adjust user permissions
    • Linux Lab#LI02-1: Export env user with grep and pipe
    • Linux Lab#LI03-1: Manage users and groups
    • Linux Lab#LI03-2: Manage files
    • Linux Lab#LI03-3: Manage software
    • Linux Lab#LI03-4: Manage hardware
    • Linux Lab#LI04-1: Bash scripting, qtool
    • Linux Lab#LI04-2: Bash scripts as terminal tool
    • Linux Lab#LI04-3: Distribute the terminal app

    • Linux readings
    • Linux Resources
  • DevOps
    • What is DevOps
    • DevOps: Introduction
    • DevOps: Agile and Microservices
    • Infrastructure as code (IaC)
    • Immutable Infrastructure
    • Software Lifecycle

    • Documentation
    • How to document: Quarto and Obsidian

    • Network protocols
    • Network: Basics
    • Network: Client-server
    • Network Protocols
    • Network: DNS
    • Network: API Rest
    • Network: gRPC
    • Network: Websocket
    • Network: SMTP
    • Network: Ping
    • Network: UDP
    • Network: webhook
    • Network: SOAP
    • Network: graphQL

    • Version Control
    • Git
    • GitHub
    • Idea and GitHub 2023
    • Git and GitHub 2023 CLI

    • IDEs
    • IDE: Visual Code
    • IDE: IntellJIdea

    • DevOps tools
    • Amazon Web Services AWS
    • Docker
    • Jenkins pipelines
    • Kubernetes k8s
    • Digital Ocean
    • Nagios
    • Ansible

    • DevOps Laboratories
    • Lab 1: chat App
    • Lab 2: Spring Boot AWS AEB manually
    • Lab 3: Spring Boot and AWS S3 publisher
    • Lab 4: Spring Boot Docker/Jenkins
    • Lab 5: k8s on Digital Ocean
    • Lab 6: Spring Boot AWS codecommit

    • DevOps readings
    • DevOps Resources
  • MarkUp
    • MarkUp Languages
    • Introduction Markup
    • HTML Markup
    • Markdown Markup
    • Markdown and HTML working together, good idea?

    • Quarto Markdown
    • Quarto Markdown: basics
    • Quarto Markdown: creating
    • Quarto Markdown: publishing
    • Quarto Markdown: code & data
    • Quarto Markdown: api rest call
    • Quarto Markdown: OJS Cells
    • Quarto Markdown: cheat-sheet

    • Styling: CSS
    • Cascade Style Sheet
    • Cascade Style Sheet: Box Model and Containers
    • CSS: W3.css

    • MarkUp Languages Laboratories
    • Lab#MD01-1: Create and publish by Quarto

    • MarkUp Languages readings
    • MarkUp Languages Resources
  • Java SE
    • What is Java SE
    • Java Standard Edition: Basics
    • Java Standard Edition: Principles
    • Java MOOC Helsinki
    • Java MOOC Helsinki Syllabus

    • Java Create Project
    • Java SE: Maven
    • Java SE: Create Maven Project
    • Java SE: Project push GitHub
    • Java SE: JUnit and TDD

    • Java Concepts
    • Java SE: Class and Objects
    • Java SE: Scope
    • Java SE: static modifier
    • Java SE: Coupling and DDD
    • Java SE: Packages
    • Java SE: Abstract/Interface
    • Java SE: Java 8

    • Java Principles
    • Java SE: Encapsulation
    • Java SE: Abstraction
    • Java SE: Inherence
    • Java SE: Polymorphism

    • Java Design Patterns
    • Java Patterns: UML
    • Java Patterns: Types
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Facade
    • Bridge
    • Decorator
    • Composite
    • Observer
    • Strategy
    • State
    • Commander

    • Java SE Laboratories
    • Lab#SE00-1: Maven Person
    • Lab#SE00-2: Maven Clinic
    • Lab#SE00-3: Library Model
    • Lab#SE00-4: Abstract/Interface Human
    • Lab#SE01-1: Maven/Gradle Person and Account
    • Lab#SE01-2: Maven/Gradle Person and Account stored in JSON
    • Lab#SE02-1: Movie/Review, Model
    • Lab#SE02-2: Movie/Review, CRUD Operations
    • Lab#SE02-3: Movie/Review, factory
    • Lab#SE02-4: Movie/Review, interactivity and coupling
    • Lab#SE02-5: Movie/Review, simulate interactivity by console
    • Lab#SE03-1: Library/Book, Core-Model
    • Lab#SE03-2: Library/Book, Sprint Zero
    • Lab#SE03-3: Library/Book, Expand Model
    • Lab#SE04-1: healthyFood Restaurant, Core Model

    • Java SE readings
    • Java SE Resources
  • Python
    • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Exceptions
    • Python: Cheat-Sheets
  • JavaScript
    • JavaScript Basics
    • JavaScript: Fundamentals
    • JavaScript: Data Types
    • JavaScript: Variables
    • JavaScript: Operators
    • JavaScript: Conditionals
    • JavaScript: Loops
    • JavaScript: Functions
    • JavaScript: Arrays
    • JavaScript: Objects

    • React Framework

    • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

    • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

    • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

    • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

    • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

    • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios
    • Lab#RE02-1: Router & Hooks
    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management
    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS
    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front
    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request
    • Lab#RE07-1: traffic lights simulation

    • React JS readings
    • ReactJS Resources
  • Backend
    • Spring Legacy
    • Spring Framework
    • Spring MVC
    • Springs Servlets

    • Spring Boot Basics
    • Spring Boot: fundamentals
    • Spring Boot: create a Project
    • Spring Boot: H2 DB and Thymeleaf
    • Spring Boot: cycle

    • Spring Boot Concepts
    • Spring Boot: Dependency Injection
    • Spring Boot: Annotations
    • Spring Boot: Controller
    • Spring Boot: View
    • Spring Boot: Thymeleaf
    • Spring Boot: Vaadin Flow
    • Spring Boot: Vaadin Hilla
    • Spring Boot: Model
    • Spring Boot: Rest
    • Spring Boot: Data & DB
    • Spring Boot: JPA & DI
    • Spring Boot: JPA Mappings
    • Spring Boot: JPA Relationships
    • Spring Boot: JPA Queries
    • Spring Boot: JPA Inherence
    • Spring Boot: Scaling

    • Spring Boot Laboratories
    • Lab#SB00-1: Library UML
    • Lab#SB00-2: CRUD User
    • Lab#SB00-3: LibraryManagement
    • Lab#SB00-4: API Rest
    • Lab#SB00-5: Rest & JPA-H2
    • Lab#SB00-6: Rest & MongoDB
    • Lab#SB00-7: Styling
    • Lab#SB01-1: DataBase
    • Lab#SB02-1: JPA Relationships
    • Lab#SB03-1: APIs & cloud
    • Lab#SB04-1: JPA Inherence
    • Lab#SB05-1: API Rest
    • Lab#SB06-1: employeeCourse
    • Lab#SB07-1: monitor Book
    • Lab#SB08-1: Restaurant UML
    • Lab#SB08-2: Vaadin
    • Lab#SB08-3: H2 and API Rest
    • Lab#SB08-4: JPA
    • Lab#SB08-5: Test API Rest
    • Lab#SB09-1: SpringIO Conference

    • Spring Boot readings
    • Spring Boot Resources
  • Learning
    • Vocabulary
    • General Vocabulary
    • SCRUM Vocabulary
    • DevOps Vocabulary
    • Java SE Vocabulay
    • Spring Boot Vocabulary
    • DataBase Vocabulary
    • ReactJS Vocabulary
    • Web Vocabulary

    • Learning
    • Useful Questions
    • Learning: tips
    • Writing
    • Taking Notes
    • Comments
    • Document
    • Auto-Evaluate

    • Books & Articles
    • Books
    • Articles

    • What is SCRUM
    • SCRUM Agile Methodology
    • Agile Manifesto & Values
    • SCRUM Guide

    • Scrum Steps
    • Meetings, Impediments and Iterations
    • User stories, Tasks and Habits
    • Delivering Value & Communication
    • ScrumMaster, how it works
    • Mindset, the key to everything
    • Product Owner, how it works
    • Managing Time & Mind
    • Team & the Specialist
    • Albertus’ Dilemma
    • Before SCRUM
    • Team Dynamics
    • Emotions and Thoughts
    • Decision Making and Intuition
    • Beyond SCRUM
    • Balances, atmosphere and tools

    • Resources
    • SCRUM Resources
  • QGIS
    • QGIS basics
    • QGIS: basic concepts

    • QGIS laboratories
    • QGIS Laboratory 1: Introduction to Open Source GIS
  • ArcGIS Pro
    • ArcGIS Pro basics
    • ArcGIS Pro: basic concepts

    • ArcGIS Pro laboratories
    • ArcGIS Pro Laboratory 1: Getting Started
  • Bookmarks
    • Online Resources
    • Online Resources
  • About
    • About me and this site
    • About me
    • About this site
    • About images credit
  • Maps
  • Featured Projects
    • ✈️ Flight tracker
    • 🧑 People tracker
    • 🚗 Renting Car
    • Email
    • GitHub
    • LinkedIn
  1. Python Basics
  2. Python: Higher-order Functions
  • Python

  • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Exceptions
    • Python: Cheat-Sheets

On this page

  • 1 Overview
  • 2 Higher-order Functions
  • 3 Lambdas
  • 4 What Are Lambdas Useful For Then?
  • 5 Python’s Higher-Order Functions
    • 5.1 Sorted
  • 6 Max
  • 7 Map
  • 8 Filter
  • 9 Reduce
  • 10 Exercises
    • 10.1 Map
    • 10.2 Filter
    • 10.3 Reduce
    • 10.4 Combinations
  • Edit this page
  • View source
  • Report an issue
  1. Python Basics
  2. Python: Higher-order Functions

Python: Higher-order Functions

Python Higher-order Functions

python
functions
The file system is organized into a hierarchical structure, starting with the root directory
Author

Isaac Boixaderas

Published

Sunday, June 1, 2025

Modified

Sunday, November 16, 2025

1 Overview

📘 Higher-order functions in Python

Higher-order functions in Python are functions that either take other functions as arguments, return functions as their result, or both. They are a fundamental concept in functional programming, enabling the creation of more modular, flexible, and reusable code by allowing functions to be treated as first-class citizens.

These functions serve as a powerful abstraction tool since they facilitate dynamic behavior, such as applying different functions to data, generating new functions on-the-fly, or combining multiple functions in various ways. They can manipulate and operate on other functions, allowing for more expressive and concise code structures, and can be stored in variables, data structures, or used as return values from other functions.

In practical terms, higher-order functions support operations like function composition, function chaining, and conditional function application, all of which contribute significantly to code clarity and efficiency. Examples include functions that accept other functions as parameters to define custom behaviors or those that generate new functions based on specific input parameters, thus enabling flexible and dynamic programming patterns.

Overall, the power of higher-order functions stems from their ability to abstract over actions and behaviors, leading to code that is more modular, transparent, and adaptable to various programming tasks.

2 Higher-order Functions

  • They are functions that take functions as arguments and/or return a function.
  • Example of function that takes a function as an argument:
def higher_order_fun(number, fun):
    return fun(number)

  • Example of function that takes a function as an argument:
def higher_order_fun(number, fun):
    return fun(number)
def square(n):
    return n ** 2

output = higher_order_fun(5, square)
print(output)
25

  • Example of function that returns a function:
def higher_order_fun_2(number):

    def inside_fun():
        return number + 10

    return inside_fun

  • Example of function that returns a function:
def higher_order_fun_2(number):

    def inside_fun(number2):
        return number + number2 + 2

    return inside_fun
output = higher_order_fun_2(5)
print(output)  # output is a function
<function higher_order_fun_2..inside_fun at 0x749cc3373130>
nums_sum = output(1)
print(nums_sum)
8

3 Lambdas

  • Also known as lambda functions.
  • Defined with the lambda keyword.
  • Small, anonymous functions.
  • Specially useful for higher-order functions (next slides).
  • Syntax: lambda arguments: expression
  • The expression returns by default.

# this lambda returns an integer
square = lambda x: x * x
print(square(5))
print(square(10))
25
100

greet = lambda name, age: f"Hello, {name}! You are {age} years old."
print(greet("Alice", 30))
print(greet("Bob", 23))
Hello, Alice! You are 30 years old.
Hello, Bob! You are 23 years old.

  • We said lambda functions do not have names
  • But we are “naming” them by using the square and greet variable names.
  • This is just for the sake of the example.
  • If writting clean code, we prefer this, not lambdas:
def square(x):
    return x ** 2
def greet(name, age):
    return f"Hello, {name}! You are {age} years old."

4 What Are Lambdas Useful For Then?

  • Perfect with higher-order functions.
  • Defined in a single line and without a name.
  • Ideal when the function is not reused anywhere else.
  • Think of them as: funciones de usar y tirar.

5 Python’s Higher-Order Functions

  • Common higher-order functions in Python:
    • sorted(), max(), map(), reduce(), filter()…

5.1 Sorted

  • The sorted() function has an optional key parameter.
  • It lets you customize the sort order by providing a function that returns a value to use for sorting purposes.

5.1.1 Example 1: Sorting a List of Dictionaries

  • This crashes, as python cannot compare inequalities between dictionaries:
data = [
    {"name": "John", "age": 35},
    {"name": "Doe", "age": 25},
    {"name": "Jane", "age": 30}
]

sorted_data = sorted(data)
TypeError: ‘<’ not supported between instances of ‘dict’ and ‘dict’

  • Using the key parameter in sorted().
data = [
    {"name": "John", "age": 35},
    {"name": "Doe", "age": 25},
    {"name": "Jane", "age": 30}
]

sorted_data = sorted(data, key=lambda x: x['age'])
print(sorted_data)
[{‘name’: ‘Doe’, ‘age’: 25}, {‘name’: ‘Jane’, ‘age’: 30}, {‘name’: ‘John’, ‘age’: 35}]

5.1.2 Example 2: Sorting a List of Tuples

data = [("apple", 3), ("banana", 1), ("cherry", 2)]

sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)
[(‘banana’, 1), (‘cherry’, 2), (‘apple’, 3)]

  • Or in reverse order using the reverse optional parameter:
data = [("apple", 3), ("banana", 1), ("cherry", 2)]

sorted_data = sorted(data, key=lambda x: x[1], reverse=True)
print(sorted_data)
[(‘apple’, 3), (‘cherry’, 2), (‘banana’, 1)]

  • How does this sort the data if we set x[0] instead of x[1] in the lambda?
data = [("apple", 3), ("banana", 1), ("cherry", 2)]

sorted_data = sorted(data, key=lambda x: x[0])
print(sorted_data)
[(‘apple’, 3), (‘banana’, 1), (‘cherry’, 2)]

  • How does this sort the data if we set x[0] instead of x[1] in the lambda?
data = [("apple", 3), ("banana", 1), ("cherry", 2)]

sorted_data = sorted(data, key=lambda x: x[0])
print(sorted_data)
[(‘apple’, 3), (‘banana’, 1), (‘cherry’, 2)]

  • Without lambdas things would be less comfortable (but doable).
def get_first_element(seq):
    return seq[0]

data = [("apple", 3), ("banana", 1), ("cherry", 2)]

sorted_data = sorted(data, key=get_first_element)
print(sorted_data)
[(‘apple’, 3), (‘banana’, 1), (‘cherry’, 2)]

5.1.3 Example 3: Sorting by Length of Strings

data = ["apple", "banana", "pear"]

sorted_data = sorted(data, key=lambda x: len(x))
print(sorted_data)
[‘pear’, ‘apple’, ‘banana’]

  • Equivalently, we could omit the lambda entirely:
data = ["apple", "banana", "pear"]

sorted_data = sorted(data, key=len)
print(sorted_data)
[‘pear’, ‘apple’, ‘banana’]

6 Max

  • By default, max of alphabetical order (the last one):
data = ["apple", "banana", "pear"]

max_word = max(data)
print(max_word)
pear

  • Accepts key argument.
  • Maximum in terms of length:
data = ["apple", "banana", "pear"]

max_word = max(data, key=len)
print(max_word)
banana

7 Map

  • Applies a given function to each item in a sequence.
  • Returns an iterable (a map object).
  • You can convert the map object to a list or tuple if needed.
  • Syntax: map(function, sequence)
  • Converting to a list: list(map(function, sequence))
  • Traditionally, for applying a function to each element we use a for loop.
def doubler(num):
    return num * 2

items = [1, 2, 3, 4, 5]
doubles = []
for i in items:
    doubles.append(doubler(i))

doubles
[2, 4, 6, 8, 10]

  • Using map():
map_obj = map(lambda n: n * 2, items)
# Convert the map object to a list
doubles = list(map_obj)
doubles
[2, 4, 6, 8, 10]

  • Or we could also use the doubler function if it is already defined:
# Convert the map object to a list
doubles = list(map(doubler, items))
doubles
[2, 4, 6, 8, 10]

8 Filter

  • Filters the elements in a sequence based on a given function that returns a boolean value.
  • Keeps the elements for which the function returns True and discards the others.
items = [1, 2, 3, 4, 5, 6]

filter_obj = filter(lambda n: n % 2 == 0, items)
even_numbers = list(filter_obj)
even_numbers
[2, 4, 6]

9 Reduce

  • The reduce function is part of the functools module.
  • Applies a given function cumulatively to the items in a sequence from left to right.
  • Reduces the sequence to a single value.

Reduce function in python

Reduce function in python
From: https://www.alpharithms.com/
import functools
items = [1, 2, 3, 4, 5]
factorial = functools.reduce(lambda x, y: x * y, items)

print(factorial)
120

10 Exercises

10.1 Map

What is printed?

What is printed?

10.2 Filter

What is printed?

Filter all the prime numbers from a given integer list. You can use a function implemented for checking if a given number is prime or not.

10.3 Reduce

What is printed?

What is printed?

Use the reduce function from the functools module to find the longest word in a list of words. If there are multiple words with the same length, any of those words is fine.

10.4 Combinations

Get the squared elements of a list, but only include those whose square results in an odd number. Use map() and filter() functions to solve this problem.

Back to top
Python: Functions
Python: Variable Scope

License: CC0 1.0 Universal

Per aspera, ad astra

  • Edit this page
  • View source
  • Report an issue