Member-only story
A crash course in Python “comprehensions” and “generators”
Master them in 20 minutes. Use them every day.
I love Python’s list comprehensions and generators.
They keep my code concise. They’re great one-liners for exploring and “munging” data. They’re intuitive, and once you know what you’re looking at, very easy to read.
Haven’t heard of them? Read on! Think you know all the variations of this popular Python construct already? Read on…
Spoiler Alert: There’s a great little video at the end of this article designed to help intermediate level coders with nested list comprehensions…
So… what are “comprehensions” exactly?
The best way of explaining these little beauties is to show you what they’re intended to replace and improve on. Instead of this traditional for
loop:
>>> fruits = ["apples", "bananas", "pears", "pears"]
>>> new_words = []
>>> for word in fruits:
... new_words.append(word.title())
...
>>> new_words
['Apples', 'Bananas', 'Pears', 'Pears']
You can just write:
>>> [word.title() for word in fruits]
['Apples', 'Bananas', 'Pears', 'Pears']