Python
(파이썬) 내장함수 enumerate() 열거 객체
코딩ABC
2023. 12. 23. 17:42
반응형
파이썬 내장함수(Built-in Function)인 enumerate 함수에 대해 알아보겠습니다.
enumerate(iterable, start=0) |
열거 객체를 반환합니다.
iterable은 시퀀스, 반복자 또는 반복을 지원하는 다른 객체여야 합니다. enumerate()가 반환한 반복자의 __next__() 메서드는 개수(기본값은 0인 시작부터)와 iterable을 반복하여 얻은 값을 포함하는 튜플을 반환합니다.
seasons = ['Spring', 'Summer', 'Fall', 'Winter'] list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] |
다음과 동일합니다.
def enumerate(iterable, start=0): n = start for elem in iterable: yield n, elem n += 1 |
반응형