Use the built-in function enumerate() to access the index in a for loop while iterating a list in Python.
for idx, val in enumerate(ints): print(idx, val)
Note: Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic. Check out PEP 279 for more.
Example iterate list with index in Python
Simple example code gets the index with the element as you iterate:
ints = [55, 44, 33, 22, 11] for idx, val in enumerate(ints): print(idx, val)
Another example iterates through indexes of the list of string
items = ['Cricket', 'Chess', 'football'] for index, item in enumerate(items): print(index, item)
Using for loop with index.
Note: Python indexes start at zero.
colors = ["red", "green", "blue", "purple"] for i in range(len(colors)): print(i, colors[i])
Do comment if you have any doubts or suggestions on this Python iteration topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.