Access index value in a for loop
Problem description
How to access the index value while iterating over a sequence with a for loop?
Problem solution
The most "pythonic" way to do that is using Python's built-in enumerate() function, which iterates through each item in an iterable sequence such as a list and returns the item's index amd the item. Check the following code:
thislist=["apple", "banana", "cherry", "apple"]
for i, item in enumerate(thislist):
print(f"{i}: {item}")
The output look like this:
0: apple
1: banana
2: cherry
3: apple
If you want to start the index from specific number, you can use start parameter:
thislist=["apple", "banana", "cherry", "apple"]
for i, item in enumerate(thislist, start=2):
print(f"{i}: {item}")
And now it will look like that:
2: apple
3: banana
4: cherry
5: apple