Effective Python memo Item 10 Enumerate from range

** Notes on Effective Python ** Item 10 range to enumerate (p20 ~ 21)

When using subscripts, use enumerate rather than implementing it in a list

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

Effective Python memo Item 10 Enumerate from range
Effective Python Memo Item 3
Effective Python Memo Item 9 Consider generator expressions for large comprehensions
Effective Python Memo Item 19 Give optional behavior to keyword arguments
Python3> List generation from iterable> list (range (5))
Effective Python Memo Item 11 Use zip to process iterators in parallel
Python memo
python memo
Python memo
python memo
Python memo
Python memo
Python memo
Effective Python Memo Item 4 Write a helper function instead of a complicated expression
Effective Python memo Item 7 Use list comprehension instead of map and filter
Effective Python Memo Item 8 Avoid three or more expressions in list comprehensions
[Python] Memo dictionary
python beginner memo (9.2-10)
python enumerate function
Effective Python Memo Item 18 Use variable-length positional arguments to make the appearance cleaner
python beginner memo (9.1)
sql from python
★ Memo ★ Python Iroha
About python, range ()
[Effective Python study memo] Chapter 1: Python-style thinking (Pythonic Thinking)
[Python] EDA memo
MeCab from Python
Python 3 operator memo
[My memo] python
Python3 metaclass memo
[Python] Basemap memo
progate Python learning memo (updated from time to time)
Python beginner memo (2)
[Python] Numpy memo
[Python] Specify the range from the image by dragging the mouse
Use thingsspeak from python
python> link> range () / xrange ()
[Python] Operation of enumerate
Python class (Python learning memo ⑦)
Touch MySQL from Python 3
My python environment memo
python openCV installation (memo)
Python module (Python learning memo ④)
Operate Filemaker from Python
Use fluentd from python
Access bitcoind from python
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
Python from or import
Python test package memo
Use MySQL from Python
[Python] Memo about functions
Django memo # 1 from scratch
Run python from excel
Install python from source
Execute command from Python
About Python, for ~ (range)
python regular expression memo
Binary search (python2.7) memo
[My memo] python -v / python -V
Operate neutron from Python!