How to access the index of a for loop in Python

 

In python, if you want to access the index of a for loop, you could do with the following method.
Method 1
# method1 create a new variable n to keep track of the index
n = 0
for i in ['a','b','c','d']:
    print(str(n)+':'+i)
    n += 1
Method 2
# method2 just use the built-in enumerate() function to do the magic
for n, i in enumerate(['a','b','c','d']):
    print(str(n)+':'+i)
If you want to start counting from 1 instead of 0, you could do this:
for n, i in enumerate(['a','b','c','d'], start=1):
    print(str(n)+':'+i)

Comments

Popular posts from this blog

How to create a memory puzzle game with Python and Pygame (#005)

How to write a slide puzzle game with Python and Pygame (2020 tutorial)

Introduction to multitasking with Python #003 gevent (2020 tutorial)