11. Functional Programming#
Functional programming is a style of writing programs as transformations from inputs to outputs. Python is not a purely functional language, but it includes functional tools that help you write concise, reusable, and testable code. This chapter introduces those tools and shows when they make Python code clearer.
Learning goals: By the end of this chapter you will be able to:
Identify pure functions and avoid unnecessary side effects
Use immutability by returning new values instead of mutating existing objects
Treat functions as first-class values that can be passed to and returned from other functions
Use lambda functions with
map(),filter(), andsorted()Write list, dictionary, and set comprehensions with conditions
Build decorators to add reusable behavior to functions
Apply recursion to problems with a natural self-similar structure
Use context managers and selected
functoolsutilities in practical programs