본문 바로가기

책/파이썬 코딩의 기술

파이썬 코딩의 기술 - (7) range보다는 enumerate를 사용하라

관련  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)로 감싼다.