[expr for x in it if cond] = a for-loop folded into one line. Build the slots, see the result + the equivalent for-loop. Brackets decide list/set/dict. An…
Why it matters
Comprehensions are everywhere in Python. Reading one means knowing the order it runs in (for, if, then the expression), the order of nested fors, and that its brackets decide its kind: a list, a set, a dict, or a generator used up once.
The key idea
A comprehension is a folded for loop: for, then if, then the expression
Common mistakes
I read a comprehension left to right and mix up the order it runs in The order: for first, then if, then the expression in front. That expression is the result, but it is worked out last.
I thought (x for x in …) makes a tuple That is a generator expression: made one at a time when asked, and used up once. Want a tuple? tuple(x for x in …).
My nested comprehension became hard to read More than two fors, or it needs a comment? Write a plain loop. Comprehensions win for simple transformations.
Try it in this playground
Add an if filter at the back of your rule A kue that fails is skipped before the expression in front is worked out.
On three trays, swap the two fors NameError: the for written first runs first, so nampan does not exist yet.
Change the brackets to { } A set: the second bolu does not go in again.
Write a dict comprehension, say {k: len(k) for k in etalase} The same key twice? The last value is kept.