관련 PEP
https://docs.python.org/3/whatsnew/2.3.html#pep-279-enumerate

range
The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.
https://docs.python.org/3/library/stdtypes.html#range
enumerate
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
일반적인 사용 예
# range
colors = ['r', 'g', 'b']
for color in colors:
print(color)
for i in range(len(colors)):
print(colors[i])
...
r
g
b
# enumerate
colors = ['r', 'g', 'b']
for index, color in enumerate(colors):
print(index, color)
...
0 r
1 g
2 b
>>> for index, color in enumerate(colors, 2):
print(index, color)
...
2 r
3 g
4 b
타입
>>> enumerate(colors)
<enumerate object at 0x100b114c8>
>>> range(len(colors))
range(0, 3)
>>> a = range(len(colors))
>>> type(a)
<class 'range'>
enumerate는 이터레이터를 지연 계산 제너레이터(lazy generator)로 감싼다.
'책 > 파이썬 코딩의 기술' 카테고리의 다른 글
파이썬 코딩의 기술 - (22) 변수 위치 인자를 사용해 시각적인 잡음을 줄여라 (0) | 2023.02.17 |
---|---|
파이썬 코딩의 기술 - (21) 변수 영역과 클로저의 상호작용 방식을 이해하라 (0) | 2023.02.17 |
파이썬 코딩의 기술 - (8) 여러 이터레이터에 대해 나란히 루프를 수행하려면 zip을 사용하라 (0) | 2023.02.15 |