The built-in Python enumerate function is a better way to access the for loop index.
How to access for loop index in Python:
The builtin enumerate
function available in both Python 2,3
versions, so that the legacy python users can also use this function.
if __name__ == '__main__':
languages = ['python', 'perl', 'groovy', 'java', 'curl', 'javascript']
for num, name in enumerate(languages):
print( num, name)
Output:
0 python
1 perl
2 groovy
3 java
4 curl
5 javascript
Make sure the python indexes start at 0, so because of this we get the output starts from 0 index.
If you would like to start from the index from 1, simply add the start parameter to enumerate function like below.
if __name__ == '__main__':
languages = ['python', 'perl', 'groovy', 'java', 'curl', 'javascript']
for num, name in enumerate(languages, start=1):
print( num, name)
Output:
1 python
2 perl
3 groovy
4 java
5 curl
6 javascript
Getting the count of Loop:
Even if we want to count the iterations of the loop, the python enumerate function is the better option for this.
if __name__ == '__main__':
languages = ['python', 'perl', 'groovy', 'java', 'curl', 'javascript']
for count, name in enumerate(languages, start=1):
print(name)
print(f'There were {count} items in the list')
Output:
python
perl
groovy
java
curl
javascript
There were 6 items in the list
References:
Happy Learning 🙂