[Python] 파이썬 enumerate, zip 차이

2023. 10. 10. 08:42·Python

파이썬 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 섹션에서 확인하실 수 있습니다.

저작자표시 비영리 변경금지 (새창열림)
'Python' 카테고리의 다른 글
  • [Python] 파이썬 for문과 한 줄for문 (List Comprehension) 차이
  • [Python] set과 drop_duplicates 중복 값 처리의 차이점
  • [Python] 파이썬 join()과 split() 함수 차이점
  • [Python] 파이썬 removeprefix, removesuffix 란?
hyunicecream
hyunicecream
안녕하세요. 여러가지 정보를 통해 조금이나마 도움이 되고자 시작하게 되었습니다.
  • hyunicecream
    Café
    hyunicecream
  • 홈
  • 포스팅 카테고리

    • 분류 전체보기
      • 생성형 AI
        • ChatGPT
        • Claude AI
        • MS Copilot
        • Perplexity
        • 생성형 AI 정보
        • 프롬프트 작성 가이드
        • AI 활용기
      • Notion
      • 업무 생산성
      • Python
        • pandas
      • 머신러닝
      • 딥러닝
      • Terminal
      • SQL
        • Postgre SQL
      • 여행정보
        • 국내여행
  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
hyunicecream
[Python] 파이썬 enumerate, zip 차이
상단으로

티스토리툴바