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:
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.
for
loop into a comprehensionThe 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.
Need to fill-in gaps in your Python skills?
Sign up for my Python newsletter where I share one of my favorite Python tips every week.
Need to fill-in gaps in your Python skills? I send weekly emails designed to do just that.