C
Python/Intermediate/Lesson 09

List Comprehension

30 min·theory
This chapter
1/8
Python

List Comprehension

🎯 After Reading This Lesson

After reading this lesson, you will be able to confidently do the following three things.

  • ✅ List slicing + comprehension
  • ✅ Choosing between list and tuple + deep copy (copy.deepcopy)
  • sort vs sorted (whether the original is modified)

Keep these learning goals as a checklist, and close the lesson once you can answer all of them.

6 List Comprehension Patterns — Code + Output

[expression for variable in iterable if condition] — a one-liner syntax for building lists. The essence of Python.

💻 Bad Example — Complex Nested Comprehension
# Hard-to-read nested comprehension
result = [x*y for sublist in [[1,2],[3,4],[5,6]] for x in sublist for y in range(x) if y % 2 == 0]
# Meaning not immediately clear

# Unnecessary comprehension — use sum() for simple sums
total = sum([x**2 for x in range(100)])  # List creation unnecessary
# Instead: sum(x**2 for x in range(100)) — generator directly
💻 Good Example — Using All Four Comprehension Types
# List comprehension
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)  # [0, 4, 16, 36, 64]

# Conditional expression (ternary)
labels = ['Even' if x % 2 == 0 else 'Odd' for x in range(5)]
print(labels)  # ['Even', 'Odd', 'Even', 'Odd', 'Even']

# Dictionary comprehension
users = [{'id': 1, 'name': 'Hong Gildong'}, {'id': 2, 'name': 'Kim Cheolsu'}]
user_map = {u['id']: u['name'] for u in users}  # {1: 'Hong Gildong', 2: 'Kim Cheolsu'}

# Dictionary key/value swap
original = {'a': 1, 'b': 2, 'c': 3}
swapped = {v: k for k, v in original.items()}  # {1: 'a', 2: 'b', 3: 'c'}

# Set comprehension — automatic duplicate removal
words = ['apple', 'banana', 'apple', 'cherry']
first_letters = {w[0] for w in words}  # {'a', 'b', 'c'}

# Generator expression — memory efficient
total = sum(x**2 for x in range(1_000_000))  # Does not create a list

# Nested comprehension — up to 2 levels is fine
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in matrix for x in row]  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 3 or more levels of nesting should use for loops
cube_coords = []
for x in range(3):
    for y in range(3):
        for z in range(3):
            cube_coords.append((x, y, z))  # Prioritize readability

🐍 Try It Out — List Comprehension

Run the concepts above as actual code. The fastest way to learn is to change values and observe how the behavior changes firsthand.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try Asking AI Like This

Knowing the concepts in this lesson lets you give AI specific instructions. Instead of a vague 'fix this,' you can make vocabulary-driven requests — and that is where token savings begin.

  • 'Convert this for + append into a list comprehension.'
  • 'Check whether a deep copy (copy.deepcopy) is needed in this code.'

Why This Reduces Tokens

Without understanding the concepts, you have to ask 'What does that mean?' after every AI response. Those follow-up questions eat up tokens. Learn the concept once, and the conversation ends in a single exchange.

List Comprehension - Python