# Python List Comprehension — Explained Simply

Yeeun·2025년 4월 17일

Python

목록 보기
8/31

Python List Comprehension — Explained Simply

List comprehension is a compact and readable way to create lists in Python. The syntax might feel tricky at first, but once understood, it becomes a powerful tool for writing cleaner code.

🔹 Basic Syntax

[expression for item in iterable if condition]
  • expression: what you want to store in the new list
  • item: variable name for each element in the iterable
  • iterable: a sequence (like a list, range, etc.) to loop through
  • condition (optional): filters which elements are included

🔹 Common Examples

✅ Get Even Numbers

[x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]

🔍 Breaking it down:

  • range(10): This generates numbers from 0 to 9.
  • for x in range(10): Loop through each number in the range and name it x.
  • if x % 2 == 0: Only include numbers that are divisible by 2 (even).
  • x: Since no transformation is needed, we store each qualifying number as-is.

✅ Square All Numbers

[x**2 for x in [1, 2, 3, 4]]  # [1, 4, 9, 16]

🔍 Breaking it down:

  • [1, 2, 3, 4]: This is the original list.
  • for x in ...: We're looping over each number and calling it x.
  • No filter condition is used.
  • x**2: We square each number and add the result to the list.

✅ Filter Strings Starting with 'a'

[s for s in ["apple", "banana", "apricot"] if s.startswith("a")]  # ['apple', 'apricot']

🔍 Breaking it down:

  • ["apple", "banana", "apricot"]: This is the original list.
  • for s in ...: We're looping over each item in the list and naming each item s.
  • if s.startswith("a"): This filters the items — we only keep s if it starts with "a".
  • s at the beginning means each matching item will be included in the result list as-is.

🔹 Nested Comprehensions (2D Arrays)

[[i * j for j in range(1, 4)] for i in range(1, 4)]  # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

🔍 Breaking it down:

  • range(1, 4): Gives us 1, 2, 3.
  • Inner loop: for j in range(1, 4) → generates [i*j for j in range(1, 4)] for a fixed i.
  • Outer loop: for i in range(1, 4) → applies the inner loop three times.
  • i * j: For each pair (i, j), multiply the numbers.
  • Result: A 2D array where each row corresponds to a different i multiplied by each j.

🔹 Real Example: Filter and Sort

Problem: Return a sorted list of elements divisible by a given divisor. If none found, return [-1].

✅ With List Comprehension

arr = [5, 9, 7, 10]
divisor = 5
result = sorted([x for x in arr if x % divisor == 0])
if not result:
    result = [-1]
print(result)  # [5, 10]

🔍 Breaking it down:

  • [x for x in arr if x % divisor == 0]: Filters out elements from arr that are divisible by divisor.
  • sorted(...): Sorts the filtered result in ascending order.
  • if not result: If the filtered list is empty, replace it with [-1].
  • print(result): Displays the final list.

🔹 Java Equivalent (For Comparison)

List<Integer> result = new ArrayList<>();
for (int n : arr) {
    if (n % divisor == 0) result.add(n);
}
if (result.isEmpty()) result.add(-1);
Collections.sort(result);

🔹 Summary

  • You must place the output expression (what to store) before the for loop.
  • You can add conditions at the end using if.
  • List comprehensions help make your code cleaner and more readable.

Use them wisely, especially for one-liners or simple filters and transformations!

0개의 댓글