Python List Comprehensions: Read Them as For-Loops
TL;DR: A list comprehension like [n*n for n in range(5)] does the same thing as a small for-loop. It just writes the result first and the source second, which is the opposite of the order you’d write the loop in. If something trips you up, it’s probably that reversal, not the concept. Translate it back into a for-loop and most of the mystery tends to go away. Seeing [x for x in data if x > 0] for the first time and pausing for a second seems like a pretty normal reaction. It doesn’t look like the statements you’ve been writing. No colon, no indentation, and the for has wandered into the middle. Plenty of tutorials just say “this is a list comprehension, it’s very Pythonic” and move on, but I’m not sure that line actually helps anyone read the thing. ...