List Comprehension - Python's Sweetest Syntax Sugar

Python基础 Apr 24, 2020

Python list comprehensions are pure sugar

A colleague saw my code and asked if it was Python or an alien language. I had a 3-level nested list comprehension with filters. [x*y for x in range(10) for y in range(10) if x%2==0 if y%3==0]

List comprehension = for loop + append in one line. [i**2 for i in range(1,11)] vs 3 lines of for loop. Code reduced 66%, coolness increased 200%.

Use list comps over map/filter. list(map(lambda x: x**2, filter(...))) makes colleagues want to hit you. [x**2 for x in nums if x%2==0] makes them buy you coffee. Readability matters.

Advanced: flat = [x for row in matrix for x in row], dict/set comprehensions. But don't nest beyond 2 levels - you're writing a puzzle, not code.

Like instant noodles - convenient but don't overdo it. Python Zen: Flat is better than nested. Translation: don't get fancy.

Tags