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.
forloop into a comprehension
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.
Hello friendly web visitor! 👋
This page is part of Python Morsels, an online Python skill-building service.
The best way to learn is by doing. In the case of Python that means writing Python code. If you'd like to improve your Python skills every week, try out Python Morsels by entering your email below to create an account.
Python Morsels topics pages are free and the first month's worth of exercises is free as well. You don't need to enter payment details to sign up.
You can find explanations of many other Python topics by signing up below.