[Python] iterator 표준 라이브러리

KangHo Lee's avatar
May 30, 2025
[Python] iterator 표준 라이브러리

📦 itertools 주요 함수 요약 + 예제

함수
설명
count(start=0, step=1)
무한히 증가하는 숫자 생성
cycle(iterable)
iterable을 무한 반복
repeat(elem, n)
요소를 n번 반복
accumulate(iterable)
누적합 또는 누적 계산
chain(*iterables)
여러 iterable을 하나로 연결
combinations(iterable, r)
r개 조합 (순서X, 중복X)
permutations(iterable, r)
r개 순열 (순서O, 중복X)
product(iterable, repeat=r)
데카르트 곱 (중복O)
combinations_with_replacement(iterable, r)
r개 조합 (순서X, 중복O)
zip_longest(*iterables, fillvalue=None)
짧은 iterable을 자동으로 채워서 zip

✅ 예제 코드

1. count()

from itertools import count for i in count(3, 2): # 3부터 2씩 증가 print(i) if i > 10: break

2. combinations()

from itertools import combinations data = ['A', 'B', 'C'] for c in combinations(data, 2): print(c)
('A', 'B') ('A', 'C') ('B', 'C')

3. permutations()

from itertools import permutations data = ['A', 'B', 'C'] for p in permutations(data, 2): print(p)
('A', 'B') ('A', 'C') ('B', 'A') ('B', 'C') ('C', 'A') ('C', 'B')

4. zip_longest()

from itertools import zip_longest a = [1, 2, 3] b = ['a', 'b'] zipped = list(zip_longest(a, b, fillvalue='없음')) print(zipped)
[(1, 'a'), (2, 'b'), (3, '없음')]
  • 일반 zip()은 짧은 쪽 기준으로 멈추지만,
  • zip_longest()긴 쪽 기준으로 끝까지 가고, 부족한 값은 fillvalue로 채웁니다.

🔚 정리

  • itertools는 반복 작업을 간결하고 효율적으로 만들어 줍니다.
  • 조합, 순열, 누적합, 무한 반복, 리스트 채우기 등 다양하게 활용 가능
  • 특히 zip_longest()길이가 다른 리스트 병합에 매우 유용합니다.
Share article

devleekangho