Posts

Showing posts with the label Python(enumerate)

How to access the index of a for loop in Python

Image
  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)