enumerate()
함수는 for문에서 (index, element)
쌍으로 순회하는데 사용되는 함수입니다.
1. index와 함께 for 루프
enumerate(list)
는 (index, element)
쌍으로 순회할 수 있도록 합니다.
아래와 같이 for i, variable
로 선언하면, 튜플이 Unpacking 되어 index와 variable에 값이 할당됩니다.
fruits = ['apple', 'kiwi', 'mango', 'melon']
for i, fruit in enumerate(fruits):
print(f'Index: {i}, Fruit: {fruit}')
Output:
Index: 0, Fruit: apple
Index: 1, Fruit: kiwi
Index: 2, Fruit: mango
Index: 3, Fruit: melon
2. 시작하는 index 숫자 변경
위의 예제에서 index는 0부터 시작하는데, 다른 이유로 index를 1부터 시작하게 만들고 싶을 수가 있습니다.
이럴 때는, 아래와 같이 enumerate()
의 인자로 start=n
을 전달하면 첫번째 index가 n
부터 시작합니다.
fruits = ['apple', 'kiwi', 'mango', 'melon']
for i, fruit in enumerate(fruits, start=1):
print(f'Index: {i}, Fruit: {fruit}')
Output:
Index: 1, Fruit: apple
Index: 2, Fruit: kiwi
Index: 3, Fruit: mango
Index: 4, Fruit: melon
3. for문에서 Tuple로 순회
아래와 같이 for문에서 Tuple로 직접 값을 받을 수도 있습니다.
튜플의 첫번째 값이 index이고, 두번째 값이 리스트의 요소 값이 됩니다.
fruits = ['apple', 'kiwi', 'mango', 'melon']
for fruit in enumerate(fruits):
print(fruit)
print(f'Index: {fruit[0]}, Fruit: {fruit[1]}')
Output:
(0, 'apple')
Index: 0, Fruit: apple
(1, 'kiwi')
Index: 1, Fruit: kiwi
(2, 'mango')
Index: 2, Fruit: mango
(3, 'melon')
Index: 3, Fruit: melon
Loading script...
Related Posts
- Python 에러 해결, 'conda' 용어가 cmdlet, 함수, 스크립트 ... 인식되지 않습니다.
- Python 에러 해결, AttributeError: module 'jwt' has no attribute 'encode'
- Python - assert 사용 방법
- Python - Counter로 Collection 개수 세기
- Python - enumerate(), for/index 예제
- Python - count(), len() 함수
- Python - join() 함수, 문자열 합치기
- Python - 줄바꿈 입력 방법
- Python - 딕셔너리를 JSON으로 변환
- Python - JSON을 딕셔너리로 변환
- Python - 딕셔너리 Index로 접근/순회 방법
- Python - 딕셔너 리 CSV 파일 쓰기/읽기
- Python - 딕셔너리 update() 함수
- Python - JSON 예쁘게(pretty), 정렬하여 출력
- Python - CSV 파일을 JSON 파일로 변환
- Python - CSV 파일을 리스트로 변환
- Python - List를 Set로 변환
- Python - Set을 List로 변환
- Python - 텍스트 파일 이어서 쓰기
- Python - 파일 끝 찾기
- Python - 파일 수정 시간, 생성 시간 확인