Comprehension is a powerful feature that simplifies working with collections such as lists, tuples and dictionaries ( any object that supports iterable
protocol). Whenever we need to perform certain operations on items in a collection, we are in the realm of comprehension. Although technically it can be achieved by using traditional for
and while
loops, comprehension expressions are more performant (by using CPython’s C core) and expressive (nested for
loops with if
).
Although comprehension was inspired by functional programming languages such as Lisp and Haskell, similar features and concepts exist in some other OOP programming languages. For example, C# supports LINQ, a powerful extension that simplifies the code drastically when working with complex collection types.