Comprehensions

In Python it's very common to build up new lists while looping over old lists. Partly this is because we don't mutate lists very often while looping over them.

There are three reasons we don't mutate lists often:

  • Python's functions use a call-by-assignment style which means mutating lists passed to us might upset the caller of our function
  • Adding things to lists or removing things from lists can cause issues while looping
  • Python makes it difficult to mutate lists (we have to go out of our way to get the index of the current item while looping)

Because we build up new lists from old ones so often, Python has a special syntax to help us with this very common operation: list comprehensions.

See below for resources on list comprehensions set comprehensions, dictionary comprehensions, and [generator expressions.

Screencasts on comprehensions

The first resource, Comprehensible Comprehensions is the one I'd most recommend if you're up for 30 minutes of video. If you need something text-based or shorter, you might want to check out the second resource, my article on comprehensions.

A Python Tip Every Week

Need to fill-in gaps in your Python skills? I send weekly emails designed to do just that.