Comprehensions and Next Steps
A list comprehension builds a new list in one short line. It is one of Python's most loved features.
A very common job is: take a list, keep some items, maybe change each one, and make a new list. With a normal loop that takes four lines: make an empty list, loop, check, append. A comprehension says the same thing in one readable line: [what for item in list if condition].
Read it from the middle: "for each p in prices, if p is under 1000, keep p". Use comprehensions for short, simple transformations. If the logic gets long, a normal loop is easier for others to read.
The same idea works for dictionaries:
A small program putting it all together
This last example uses almost everything from this course: a list of dictionaries (the cart), a function, a calculation inside sum(), an f-string, and an if. Real programs are just these same building blocks, combined in bigger ways. If you understand this example, you're ready for the intermediate lessons.
What to learn next
- Virtual environments (
python -m venv) to keep each project's packages separate. - Web apps with Flask, Django or FastAPI.
- Data with pandas and charts with matplotlib.
- Automation: renaming files, reading spreadsheets and calling web APIs.
[x for x in items if condition]builds a new list in one line.- Dictionary comprehensions work the same way:
{k: v for ...}. - Prefer a normal loop when the logic gets complicated.
