💻 Programming

Comprehension

Comprehension

Python's concise syntax for creating lists, dictionaries, and sets. Written in the form [x for x in iterable].

📖 Detailed Explanation

A comprehension is a syntax in Python for concisely creating lists, dictionaries, sets, and generators. It compresses for loops and conditionals into a single line, allowing you to write highly readable code, and it generally runs faster than the equivalent for loop.

A list comprehension is written in the form [expression for item in iterable if condition]. For example, [x*2 for x in range(10) if x%2==0] creates a list that picks only the even numbers from 0 to 9 and doubles them. Nested loops are also possible, which is useful for processing two-dimensional data.

A dictionary comprehension has the form {key: value for item in iterable}. It is used to transform an existing dictionary or to build a dictionary from a list. A set comprehension uses curly braces as in {expression for item in iterable}, and duplicates are removed automatically.

A generator expression uses parentheses and is written in the form (expression for item in iterable). Unlike a list comprehension, it does not store all elements in memory but generates them one at a time as needed, so it is well suited to processing large amounts of data.

💻 Code Example

# 리스트 컴프리헨션
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 조건부 필터링
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# 중첩 루프
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 딕셔너리 컴프리헨션
word_lengths = {word: len(word) for word in ['apple', 'banana', 'cherry']}
# {'apple': 5, 'banana': 6, 'cherry': 6}

# 집합 컴프리헨션
unique_chars = {char.lower() for char in "Hello World" if char.isalpha()}
# {'h', 'e', 'l', 'o', 'w', 'r', 'd'}

# 제네레이터 표현식 (메모리 효율적)
sum_of_squares = sum(x**2 for x in range(1000000))

# 조건 표현식과 함께
labels = ['pass' if score >= 60 else 'fail' for score in [75, 42, 88, 55]]
# ['pass', 'fail', 'pass', 'fail']

🗣️ Examples of Practical Conversations

Senior: This data filtering logic is a bit long. I think we can shorten it with a comprehension.

Junior: Five lines of for loop into one line?

Senior: Yes, but if it gets too complex, readability actually suffers. A good rule is to use a comprehension if there are two conditions or fewer, and split it into a function if there are more.

Interviewer: What is the difference between a list comprehension and the map/filter functions?

Candidate: List comprehensions are more idiomatic in Python and more readable. map and filter can actually get more complicated when used with lambda. Performance is almost the same, but comprehensions are often slightly faster.

Interviewer: Are there any downsides to comprehensions?

Candidate: If you force complex logic into a single line, readability drops sharply. They are also not suitable for code with side effects.

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Reviewer: This comprehension is a bit complex. It has a nested for and even an if.

Author: I wanted to handle it in one line...

Reviewer: Unroll it into a regular for loop, or split the inner logic into a function. If someone else can't understand it within 3 seconds when reading it, it's a candidate for refactoring.

⚠️ Cautions

🔗 Related Terms

📚 Learn More