파이썬 enumerate 함수와 zip 함수의 차이
enumerate()
는 Python의 내장 함수로, 반복 가능한 객체(예: 리스트, 튜플)를 입력 받아 인덱스와 해당 요소를 함께 반환하는 반복자를 생성합니다.
zip 함수의 기본
zip()
은 여러 개의 반복 가능한 객체를 입력 받아, 동일한 인덱스를 가진 요소끼리 튜플로 묶어 반환하는 반복자를 생성합니다.
enumerate 예시 1
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 cherry
enumerate 예시 2
words = ["hello", "world", "python"]
for index, word in enumerate(words, start=1):
print(f"Word {index} is {word}")
Output:
Word 1 is hello
Word 2 is world
Word 3 is python
zip 예시 1
fruits = ['apple', 'banana', 'cherry']
colors = ['red', 'yellow', 'dark red']
for fruit, color in zip(fruits, colors):
print(fruit, "is", color)
Output:
apple is red
banana is yellow
cherry is dark red
zip 예시 2
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
jobs = ["Engineer", "Doctor", "Lawyer"]
for name, age, job in zip(names, ages, jobs):
print(f"{name} is {age} years old and works as a {job}")
Output:
Alice is 25 years old and works as an Engineer
Bob is 30 years old and works as a Doctor
Charlie is 35 years old and works as a Lawyer
enumerate와 zip 결합 예시
names = ["Anna", "Elsa", "Olaf"]
powers = ["healing", "ice", "snowman"]
for index, (name, power) in enumerate(zip(names, powers)):
print(f"{index}. {name} has the power of {power}")
Output:
0. Anna has the power of healing
1. Elsa has the power of ice
2. Olaf has the power of snowman
정리
enumerate
는 반복 가능한 객체의 인덱스와 값을 함께 반환하며, zip
은 여러 반복 가능한 객체의 동일한 위치에 있는 요소들을 묶어 반환합니다.
더 알아보기
더 자세한 정보와 사용법은 Python 공식 문서의 enumerate 및 zip 섹션에서 확인하실 수 있습니다.