Pythonic Functional Programming: List Comprehensions
In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions.
Map is a high-order function that receives another function and a collection as input and applies that function to each element in the collection, returning a new collection.
Filter is a higher-order function that processes a collection in some order to produce a new collection containing exactly those elements of the original data structure for which a given predicate returns the boolean value true.
Reduce is a high-order function that receives another function, a collection and a initial value as input, and recursively applies that function to the initial value and to each element of the collection, ultimately reducing it to a single value.
According to official Python documentation:
“A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.”
Guido van Rossum doesn't like functional programming a lot:
Guido: I'm not a fan of religiously taking some idea to the extreme, and I try to be pragmatic in my design choices (but not *too* pragmatic, see the start of this sentence :-). I value readability and usefulness for real code. There are some places where map() and filter() make sense, and for other places Python has list comprehensions. I ended up hating reduce() because it was almost exclusively used (a) to implement sum(), or (b) to write unreadable code. So we added builtin sum() at the same time we demoted reduce() from a builtin to something in functools (which is a dumping ground for stuff I don't really care about :-).
We have several sources on the reasons why list comprehensions outperform map()
and might outperform for
loops. Please check them out: