Python enumerate() 함수, 예제와 함께 설명

이 튜토리얼은 파이썬에서 enumerate() 함수를 사용하는 방법을 가르칠 것입니다.

Python의 enumerate() 함수는 인덱스와 함께 iterable의 항목에 액세스하기 위한 간결한 구문을 제공합니다.

간단한 루핑을 사용하여 항목과 인덱스에 액세스하는 방법을 검토한 다음 Python의 enumerate() 함수 구문을 학습합니다. 우리는 또한 그 과정에서 예제를 코딩할 것입니다.

의 시작하자.

Python에서 for 루프를 사용하여 반복하는 방법

한 번에 하나씩 개별 항목에 대해 반복하고 액세스할 수 있는 모든 Python 객체를 iterable이라고 합니다. 따라서 Python 목록, 튜플, 사전 및 문자열은 모두 반복 가능합니다.

아래 코드 셀에 정의된 쇼핑 목록의 예를 들어 보겠습니다.

shopping_list = ["fruits","cookies","cereals","protein bars","post-it notes"]

Python에서는 for 루프를 사용하여 모든 iterable을 반복할 수 있습니다. 이를 수행하는 구문은 다음과 같습니다.

for item in <iterable>:
    # do something on item

# item: looping variable
# <iterable>: any Python iterable: list, tuple, dictionary, string, and so on.

이제 이 구문을 사용하여 shopping_list를 반복하고 개별 항목에 액세스해 보겠습니다.

for item in shopping_list:
  print(item)

# Output
fruits
cookies
cereals
protein bars
post-it notes

이 구성은 항목에 직접 액세스하는 데 도움이 됩니다. 그러나 때때로 항목 자체 외에 항목의 인덱스에 액세스해야 할 수도 있습니다.

아래와 같이 루프 본문 내에서 증가할 수 있는 인덱스 변수를 사용할 수 있습니다.

index = 0
for item in shopping_list:
  print(f"index:{index}, {item}")
  index += 1

# Output
index:0, fruits
index:1, cookies
index:2, cereals
index:3, protein bars
index:4, post-it notes

그러나 이것은 가장 효율적인 방법이 아닙니다. 인덱스를 증가시키는 것을 기억하지 않으면 코드가 예상대로 작동하지 않습니다.

index = 0
for item in shopping_list:
  print(f"index:{index}, {item}")
  # no update of index inside loop body
  # index is never updated and is always 0

# Output
index:0, fruits
index:0, cookies
index:0, cereals
index:0, protein bars
index:0, post-it notes

for 루프를 사용하는 또 다른 일반적인 패턴은 range() 함수와 함께 사용하는 것입니다. 다음 섹션에서 이에 대해 알아보겠습니다.

  최고의 무료 NZB 검색 엔진

range() 함수를 사용하여 인덱스에 액세스하는 방법

Python의 내장 len() 함수는 Python 객체의 길이를 반환합니다. 따라서 shopping_list 인수와 함께 len() 함수를 호출하여 shopping_list의 길이(이 경우 5)를 얻을 수 있습니다.

len(shopping_list)
# Output: 5

range() 함수는 반복에서 사용할 수 있는 범위 객체를 반환합니다. 범위(중지)를 반복하면 인덱스 0, 1, 2,…, stop-1을 얻습니다.

stop = len(list)을 설정하면 유효한 인덱스 목록을 얻을 수 있습니다. 그래서 range() 함수를 이용하면 아래와 같이 인덱스와 해당 항목에 접근할 수 있습니다.

for index in range(len(shopping_list)):
  print(f"index:{index}, item: {shopping_list[index]}")

# Output
index:0, item: fruits
index:1, item: cookies
index:2, item: cereals
index:3, item: protein bars
index:4, item: post-it notes

그러나 이것은 인덱스와 항목에 동시에 액세스하는 권장되는 Python 방식이 아닙니다.

Python enumerate() 함수의 구문

Python의 enumerate() 함수를 사용하면 다음 일반 구문을 사용하여 인덱스와 함께 항목에 액세스할 수 있습니다.

enumerate(<iterable>, start = 0)

위의 구문에서:

  • 은 필수 매개변수이며 목록이나 튜플과 같은 모든 Python 이터러블이 될 수 있습니다.
  • start는 카운팅이 시작되는 인덱스를 제어하는 ​​선택적 매개변수입니다. start 값을 지정하지 않으면 기본값은 0입니다.

이제 shopping_list를 사용하여 enumerate() 함수를 호출할 수 있으며 아래 코드 셀과 같이 enumerate 객체를 반환합니다.

enumerate(shopping_list)
<enumerate at 0x7f91b4240410>

열거 개체를 반복할 수 없습니다. 이제 열거 객체를 Python 목록으로 변환해 보겠습니다.

list(enumerate(shopping_list))

# Output
[(0, 'fruits'),
 (1, 'cookies'),
 (2, 'cereals'),
 (3, 'protein bars'),
 (4, 'post-it notes')]

열거 객체의 항목에 액세스하는 또 다른 방법은 다음을 호출하는 것입니다. 다음() 함수 열거 객체를 인수로 사용합니다. Python에서 next() 함수는 반복자의 다음 항목을 반환합니다.

내부적으로 next() 함수는 연속 항목을 검색하기 위해 반복자 객체에서 __next__ 메서드를 호출하여 작동합니다.

열거형 개체를 shopping_list_enum 변수에 할당해 보겠습니다.

shopping_list_enum = enumerate(shopping_list)

shopping_list_enum으로 next()를 처음 호출하면 인덱스 0과 인덱스 0에 있는 항목인 튜플(0, ‘과일’)을 얻게 됩니다.

next() 함수에 대한 추가 호출을 계속하면 아래에 설명된 대로 인덱스와 함께 연속 항목을 얻게 됩니다.

next(shopping_list_enum)
# (0, 'fruits')
next(shopping_list_enum)
# (1, 'cookies')
next(shopping_list_enum)
# (2, 'cereals')
next(shopping_list_enum)
# (3, 'protein bars')
next(shopping_list_enum)
# (4, 'post-it notes')

모든 항목에 액세스하고 목록의 끝에 도달한 후 next() 함수를 호출하면 어떻게 됩니까? StopIteration 오류가 발생합니다.

next(shopping_list_enum)
# ---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-16-4220f68f6c7e> in <module>()
----> 1 next(shopping_list_enum)

StopIteration:

enumerate() 함수는 필요할 때만 연속적인 인덱스와 항목을 반환하고 미리 계산되지 않습니다. 메모리 효율성을 고려해야 하는 Python 프로젝트에서 큰 iterable을 반복해야 할 때 enumerate() 함수를 사용해 볼 수 있습니다.

Python enumerate() 함수 예제

이제 enumerate() 함수를 사용하는 구문을 배웠으므로 이전에 사용했던 for 루프를 수정해 보겠습니다.

이전 섹션에서 열거 객체를 반복하면 인덱스와 항목이 있는 튜플이 반환된다는 것을 알고 있습니다. 이 튜플을 index와 item의 두 변수로 압축을 풀 수 있습니다.

for index, item in enumerate(shopping_list):
  print(f"index:{index}, item:{item}")

# Output
index:0, item:fruits
index:1, item:cookies
index:2, item:cereals
index:3, item:protein bars
index:4, item:post-it notes

다음으로 사용자 지정 시작 값을 지정하는 방법을 살펴보겠습니다.

사용자 정의 시작 값으로 열거()하는 방법

Python은 0 인덱싱을 따르므로 시작 값은 기본적으로 0입니다. 그러나 사람이 읽을 수 있는 형식의 인덱스가 필요한 경우(1 또는 선택한 다른 인덱스에서 시작하는 경우) 사용자 지정 시작 값을 지정할 수 있습니다.

shopping_list 예제에서 1부터 계산을 시작하려면 start = 1로 설정합니다.

for index, item in enumerate(shopping_list,1):
  print(f"index:{index}, item:{item}")

# Output
index:1, item:fruits
index:2, item:cookies
index:3, item:cereals
index:4, item:protein bars
index:5, item:post-it notes

그러나 사용자 지정 시작 값을 지정할 때 두 번째 위치 인수로 지정해야 합니다.

iterable의 순서와 시작 값을 실수로 바꾸면 아래 코드 셀에 설명된 대로 오류가 발생합니다.

for index, item in enumerate(1,shopping_list):
  print(f"index:{index}, item:{item}")

# Output
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-5dbf7e2749aa> in <module>()
----> 1 for index, item in enumerate(1,shopping_list):
      2   print(f"index:{index}, item:{item}")

TypeError: 'list' object cannot be interpreted as an integer

이러한 오류를 방지하기 위해 아래와 같이 키워드 인수로 start를 지정할 수 있습니다.

for index, item in enumerate(shopping_list, start = 1):
  print(f"index:{index}, item:{item}")

# Output
index:1, item:fruits
index:2, item:cookies
index:3, item:cereals
index:4, item:protein bars
index:5, item:post-it notes

지금까지 Python 목록과 함께 enumerate() 함수를 사용하는 방법을 배웠습니다. enumerate 함수를 사용하여 Python 문자열, 사전 및 튜플을 반복할 수도 있습니다.

Python 튜플과 함께 enumerate() 함수를 사용하는 방법

shopping_list가 튜플이라고 가정합니다. Python에서 튜플은 Python 목록과 유사하지만 변경할 수 없는 컬렉션이기도 합니다. 따라서 수정할 수 없으며 수정하려고 하면 오류가 발생합니다.

다음 코드 조각은 shopping_list를 튜플로 초기화합니다.

shopping_list = ("fruits","cookies","cereals","protein bars","post-it notes")
type(shopping_list)
# Tuple

튜플의 첫 번째 항목을 수정하려고 하면 Python 튜플이 변경할 수 없는 컬렉션이므로 오류가 발생합니다.

shopping_list[0] = 'vegetables'

# Output
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-ffdafa961600> in <module>()
----> 1 shopping_list[0] = 'vegetables'

TypeError: 'tuple' object does not support item assignment

▶ 이제 다음 코드 스니펫을 실행하여 튜플에서 enumerate() 함수가 예상대로 작동하는지 확인합니다.

shopping_list = ("fruits","cookies","cereals","protein bars","post-it notes")
for index, item in enumerate(shopping_list):
    print(f"index:{index}, item:{item}")

Python 문자열과 함께 enumerate() 함수를 사용하는 방법

Python enumerate() 함수를 사용하여 문자열을 반복하고 문자와 인덱스에 동시에 액세스할 수도 있습니다.

다음은 예입니다.

py_str="Butterfly"
for index, char in enumerate(py_str):
  print(f"index {index}: {char}")

# Output
index 0: B
index 1: u
index 2: t
index 3: t
index 4: e
index 5: r
index 6: f
index 7: l
index 8: y

위의 출력에서 ​​문자와 인덱스(0-8)가 인쇄되었음을 알 수 있습니다.

결론👩🏽‍💻

다음은 학습한 내용을 요약한 것입니다.

  • for 루프를 사용하여 항목에 액세스하고 별도의 카운터 또는 인덱스 변수를 유지할 수 있습니다.
  • 원하는 경우 range() 함수를 사용하여 유효한 인덱스를 가져오고 목록을 인덱싱하여 항목에 액세스할 수 있습니다.
  • 권장되는 Python 방식으로 enumerate(iterable) 구문과 함께 Python의 enumerate() 함수를 사용할 수 있습니다. 기본적으로 개수 또는 인덱스는 0에서 시작합니다.
  • enumerate(iterable, start) 구문으로 사용자 정의 시작 값을 지정하여 시작 값과 해당 항목에서 시작하는 인덱스를 가져올 수 있습니다.
  • 튜플, 문자열, 사전 및 일반적으로 모든 Python iterable로 작업할 때 enumerate 함수를 사용할 수 있습니다.

enumerate() 함수에 대한 이 튜토리얼이 도움이 되었기를 바랍니다. 다음으로, 파이썬 목록에서 항목의 인덱스를 찾는 방법을 배웁니다. 계속 코딩하세요!