** Notes on Effective Python ** Item 10 range to enumerate (p20 ~ 21)
flaver_list = ['vanilla', 'chocolate', 'pecan', 'storawberry']
for i in range(len(flaver_list)):
flaver = flaver_list[i]
print('%d: %s' % (i+1, flaver))
>>>
1: vanilla
2: chocolate
3: pecan
4: storawberry
for i, flaver in enumerate(flaver_list):
print('%d: %s' % (i+1, flaver))
>>>
1: vanilla
2: chocolate
3: pecan
4: storawberry
By the way, enumerate allows you to specify the number to start counting. Using it makes the code a little easier to read.
for i, flaver in enumerate(flaver_list, 1): #Pass argument 1 to enumerate
print('%d: %s' % (i, flaver))
>>>
1: vanilla
2: chocolate
3: pecan
4: storawberry
In [ ]:
Recommended Posts