Comprehensions

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Comprehensions

Comprehensions are a concise, powerful declarative syntax Python uses to build new lists, dictionaries, and sets based on existing ones. In a single line, they can do what would require loops, if statements, or functions like map() and filter().

Basic Comprehensions

In their most basic form, comprehensions use the for and in keywords to create instructions that say, “Make a new collection by doing something to every item in this existing collection.” This form of comprehension is like a map() function but more readable.

Filtering Comprehensions With if

If you add one or more if expressions after the for…in expression, you can define criteria to include or exclude items in the collection you’re creating:

Conditional Comprehensions With if and else

If you add an if…else expression before the for…in expression, you can specify the value to be added to the new collection if a condition is met and an alternate value if the condition isn’t met.

Generators

To understand generators, you need to understand iterables and iterators.

Generators

Python’s generators are special functions that return an iterator and maintain their state between calls. They’re another feature that’s better to show than to describe.

Generator Comprehensions

In addition to list, set, and dictionary comprehensions, Python supports generator comprehensions, which are delimited by parentheses:

Using Generators for Memory Efficiency

If you need a large collection of values to iterate through, you may want to use a generator comprehension instead of a list comprehension. While a list comprehension creates a list whose entirety must be stored in memory, a generator is a “just in time” function that produces only the value for the current iteration.

The zip() Function

zip() is a useful built-in function that combines two iterables into a single iterator of tuples. Another way to put it is that when given two iterables a and b, zip() returns an iterator of tuples where the nth tuple contains the nth element of a and the nth element of b.

See forum comments
Download course materials from Github
Previous: Sets Next: Functions: Deep Dive