← 모든 글

List Comprehension 가이드

Python List Comprehension을 기초부터 고급 활용법까지 해보자

Python 기초 · 2 / 3편

이 글의 목차

🎯 학습 목표

이 글을 통해 다음을 학습할 수 있습니다:

  • List Comprehension의 기본 문법과 구조
  • 조건문을 활용한 필터링과 변환
  • 중첩 반복문과 2차원 리스트 처리
  • 코딩테스트에서의 실전 활용법
  • 성능과 가독성을 고려한 사용 가이드

📝 List Comprehension이란?

List Comprehension은 기존 리스트나 반복 가능한 객체로부터 새로운 리스트를 생성하는 Python의 강력한 기능입니다.

기본 구조

[표현식 for 항목 in 반복가능객체]

기존 방식 vs List Comprehension

# ❌ 기존 방식 (번거로움)
numbers = []
for i in range(10):
    numbers.append(i * 2)
print(numbers)  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# ✅ List Comprehension (간결함)
numbers = [i * 2 for i in range(10)]
print(numbers)  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

🔧 기본 문법 완전 정리

1. 단순 변환

# 제곱 리스트 생성
squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

# 문자열을 대문자로 변환
words = ["python", "java", "javascript"]
upper_words = [word.upper() for word in words]
print(upper_words)  # ['PYTHON', 'JAVA', 'JAVASCRIPT']

2. 조건문으로 필터링

# 짝수만 선택
even_numbers = [x for x in range(20) if x % 2 == 0]
print(even_numbers)  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# 길이가 5 이상인 단어만 선택
words = ["python", "java", "go", "rust", "javascript"]
long_words = [word for word in words if len(word) >= 5]
print(long_words)  # ['python', 'javascript']

3. 조건부 표현식 활용

# 삼항 연산자 활용
numbers = [-2, -1, 0, 1, 2, 3]
positive_or_zero = [x if x >= 0 else 0 for x in numbers]
print(positive_or_zero)  # [0, 0, 0, 1, 2, 3]

# 성적에 따른 등급 부여
scores = [95, 87, 76, 92, 68]
grades = ['A' if score >= 90 else 'B' if score >= 80 else 'C' if score >= 70 else 'F' 
          for score in scores]
print(grades)  # ['A', 'B', 'C', 'A', 'F']

🚀 고급 활용법

1. 중첩 반복문 처리

# 2차원 리스트 생성
matrix = [[i + j for j in range(3)] for i in range(3)]
print(matrix)  # [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

# 2차원 리스트 평탄화 (flatten)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

2. 곱집합(Cartesian Product) 생성

# 색상과 사이즈의 모든 조합
colors = ['red', 'blue', 'green']
sizes = ['S', 'M', 'L']
combinations = [(color, size) for color in colors for size in sizes]
print(combinations)
# [('red', 'S'), ('red', 'M'), ('red', 'L'), 
#  ('blue', 'S'), ('blue', 'M'), ('blue', 'L'), 
#  ('green', 'S'), ('green', 'M'), ('green', 'L')]

3. 복잡한 조건 처리

# 여러 조건을 만족하는 요소 선택
numbers = range(1, 101)
special_numbers = [x for x in numbers 
                   if x % 3 == 0 and x % 5 != 0 and x < 50]
print(special_numbers)  # [3, 6, 9, 12, 18, 21, 24, 27, 33, 36, 39, 42, 48]

💡 실전 활용 예제

예제 1: 문자열 처리

# 문장을 단어별로 분리하고 길이 계산
sentence = "Python List Comprehension is awesome"
word_lengths = [(word, len(word)) for word in sentence.split()]
print(word_lengths)
# [('Python', 6), ('List', 4), ('Comprehension', 13), ('is', 2), ('awesome', 7)]

# 숫자 문자열을 정수로 변환
str_numbers = ["1", "2", "3", "4", "5"]
int_numbers = [int(x) for x in str_numbers]
print(int_numbers)  # [1, 2, 3, 4, 5]

예제 2: 딕셔너리 처리

# 학생 성적 데이터 처리
students = [
    {"name": "김파이썬", "score": 95},
    {"name": "이자바", "score": 87},
    {"name": "박자스", "score": 92},
    {"name": "최씨샵", "score": 78}
]

# 90점 이상 학생들의 이름만 추출
honor_students = [student["name"] for student in students if student["score"] >= 90]
print(honor_students)  # ['김파이썬', '박자스']

# 모든 학생의 성적에 가산점 5점 추가
bonus_scores = [student["score"] + 5 for student in students]
print(bonus_scores)  # [100, 92, 97, 83]

예제 3: 파일 처리 시뮬레이션

# 파일명 리스트에서 특정 확장자만 필터링
files = ["document.txt", "image.jpg", "script.py", "data.csv", "photo.png"]
python_files = [file for file in files if file.endswith('.py')]
image_files = [file for file in files if file.endswith(('.jpg', '.png'))]

print(f"Python 파일: {python_files}")  # Python 파일: ['script.py']  
print(f"이미지 파일: {image_files}")   # 이미지 파일: ['image.jpg', 'photo.png']

🧮 코딩테스트 실전 예제

예제 1: 소수 찾기

def is_prime(n):
    """소수 판별 함수"""
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

# 1부터 50까지의 소수 찾기
primes = [x for x in range(1, 51) if is_prime(x)]
print(f"50 이하의 소수: {primes}")
# 50 이하의 소수: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

예제 2: 좌표 변환

# 2D 좌표 변환 및 필터링
points = [(1, 2), (3, 4), (5, 6), (7, 8), (2, 3)]

# x + y가 짝수인 점들을 2배 확대
transformed_points = [(x*2, y*2) for x, y in points if (x + y) % 2 == 0]
print(f"변환된 좌표: {transformed_points}")  # 변환된 좌표: []
# 입력의 모든 점은 x + y가 홀수이므로 선택되는 점이 없습니다.

# 원점에서의 거리가 5 이하인 점들
close_points = [(x, y) for x, y in points if (x**2 + y**2)**0.5 <= 5]
print(f"가까운 점들: {close_points}")  # 가까운 점들: [(1, 2), (3, 4), (2, 3)]

예제 3: 패턴 매칭

# 특정 패턴을 가진 문자열 찾기
words = ["apple", "application", "apply", "banana", "appreciate", "approach"]

# 'app'로 시작하는 단어들
app_words = [word for word in words if word.startswith("app")]
print(f"'app'로 시작: {app_words}")
# 'app'로 시작: ['apple', 'application', 'apply', 'appreciate', 'approach']

# 'a'로 시작하고 'e'로 끝나는 단어들
a_to_e_words = [word for word in words if word.startswith('a') and word.endswith('e')]
print(f"'a'로 시작하고 'e'로 끝남: {a_to_e_words}")
# 'a'로 시작하고 'e'로 끝남: ['apple', 'appreciate']

⚡ 성능과 활용 팁

1. 메모리 효율성 고려

# ✅ 작은 데이터: List Comprehension 사용
small_squares = [x**2 for x in range(100)]

# ✅ 큰 데이터: Generator Expression 사용 (메모리 절약)
large_squares = (x**2 for x in range(1000000))  # 괄호 사용

# 필요할 때만 값을 생성
for square in large_squares:
    if square > 1000:
        print(f"첫 번째 1000 초과 값: {square}")
        break

2. 가독성 우선 원칙

# ❌ 너무 복잡한 List Comprehension (가독성 떨어짐)
complex_result = [x*2+1 if x%2==0 else x//2 for x in range(20) if x%3!=0 and x>5]

# ✅ 함수로 분리하여 가독성 향상
def process_number(x):
    """숫자 처리 로직"""
    if x % 2 == 0:
        return x * 2 + 1
    else:
        return x // 2

def is_valid_number(x):
    """유효한 숫자 판별"""
    return x % 3 != 0 and x > 5

# 깔끔한 List Comprehension
clean_result = [process_number(x) for x in range(20) if is_valid_number(x)]
print(clean_result)

3. 타입 힌트 활용

from typing import List

def filter_and_transform(numbers: List[int], threshold: int) -> List[int]:
    """숫자 리스트를 필터링하고 변환합니다."""
    return [x * 2 for x in numbers if x > threshold]

# 사용 예시
original_numbers: List[int] = [1, 5, 8, 12, 3, 9, 15]
result: List[int] = filter_and_transform(original_numbers, 7)
print(f"결과: {result}")  # 결과: [16, 24, 18, 30]

🔄 다른 Comprehension들

Dictionary Comprehension

# 숫자와 제곱 매핑
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# 문자열 길이 매핑
words = ["python", "java", "go"]
length_dict = {word: len(word) for word in words}
print(length_dict)  # {'python': 6, 'java': 4, 'go': 2}

Set Comprehension

# 중복 제거된 길이 집합
words = ["python", "java", "go", "rust", "go"]
unique_lengths = {len(word) for word in words}
print(unique_lengths)  # {2, 4, 6}

🎯 실습 문제

문제: 학생 성적 관리 시스템

# 학생 데이터
students = [
    {"name": "김파이썬", "scores": [90, 85, 92]},
    {"name": "이자바", "scores": [78, 82, 88]},
    {"name": "박자스", "scores": [95, 90, 93]},
    {"name": "최씨샵", "scores": [88, 85, 90]}
]

# 1. 각 학생의 평균 점수 계산
averages = [(student["name"], sum(student["scores"]) / len(student["scores"])) 
            for student in students]
print("평균 점수:")
for name, avg in averages:
    print(f"{name}: {avg:.1f}점")

# 2. 평균이 85점 이상인 우수 학생
honor_students = [student["name"] for student in students 
                  if sum(student["scores"]) / len(student["scores"]) >= 85]
print(f"\n우수 학생: {honor_students}")

# 3. 모든 점수를 평탄화하여 전체 최고점 찾기
all_scores = [score for student in students for score in student["scores"]]
max_score = max(all_scores)
print(f"전체 최고점: {max_score}점")

📚 정리 및 다음 단계

오늘 배운 내용

  • ✅ List Comprehension의 기본 문법과 구조
  • ✅ 조건문을 활용한 필터링과 변환
  • ✅ 중첩 반복문과 2차원 데이터 처리
  • ✅ 코딩테스트 실전 활용 패턴
  • ✅ 성능과 가독성을 고려한 사용법

다음에 학습할 내용

  • Dictionary Comprehension 심화
  • Generator Expression과 메모리 최적화
  • 함수형 프로그래밍 (map, filter, reduce)
  • 람다 함수와 고차 함수

🔗 관련 링크:


yellow.log · 2025.07.28에 작성 · 2026.09.29에 수정

Python 기초 전체 3편

  1. 1.변수와 자료형 기초 가이드
  2. 2.List Comprehension 가이드읽는 중
  3. 3.함수 정의와 활용 완전 가이드