Python List Comprehensions: Read Them as For-Loops

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. ...

2026-05-31 · 10 min read · 1973 words · KbWen · EN
Python 列表推導式:一行取代 for 迴圈

Python 列表推導式:一行取代 for 迴圈

TL;DR:列表推導式 [n*n for n in range(5)] 其實就跟一個 for 迴圈做一樣的事,只是把「結果」寫在最前面、「來源」丟到後面,順序剛好跟念中文相反。會看不懂多半不是因為它難,比較像是這個順序要花點時間習慣。能把它翻回 for 迴圈來看的話,大概就沒那麼可怕了。 第一次看到 [x for x in data if x > 0] 這種東西會愣一下,我覺得滿正常的。它長得不太像一般的句子,沒冒號、沒縮排,for 還跑到中間去。很多地方會直接說「這叫列表推導式(list comprehension),很 Pythonic」就帶過,可是那句話其實對看懂它沒什麼幫助,看完還是一樣霧。 所以這篇就不背語法了,從大家應該都會的 for 迴圈開始慢慢聊好了,不趕時間。 同一件事,兩種寫法 假設要做一個 0 到 4 的平方數清單。用 for 迴圈大概像這樣寫: squares = [] for n in range(5): squares.append(n * n) ## [0, 1, 4, 9, 16] 三行,開個空 list、跑迴圈、一個一個 append 進去。很普通,沒什麼問題,能跑就好。 換成列表推導式的話,就變這樣: squares = [n * n for n in range(5)] ## [0, 1, 4, 9, 16] 一行,結果一樣。這倒不是我隨口說的,文末附的測試檔就是把這兩種寫法的結果丟去 assertEqual 對,跑出來是相等的。所以大概可以放心把它當成上面那段 for 迴圈的縮寫,因為它字面上差不多就是那個意思,只是擠成一行而已。 怎麼讀它:翻回 for 迴圈來看 我覺得重點在閱讀順序。推導式長這樣: [ 運算式 for 變數 in 來源 ] n * n for n in range(5) 拆成三塊來看的話: ...

2026-05-31 · 4 min read · 646 words · KbWen · ZH