Accessing the index in 'for' loops
To access the index in a 'for' loop in Python, you can use the built-in 'enumerate' function. This function takes an iterable (such as a list or string) as an argument and returns a tuple containing the index and the value at each iteration.
Here is an example of using 'enumerate' in a 'for' loop:
names = ['Alice', 'Bob', 'Charlie', 'Dave']
for i, name in enumerate(names):
print(f'{i}: {name}')
This will print out the following:
0: Alice 1: Bob 2: Charlie 3: Dave
Watch a video course
Python - The Practical Guide
You can also access the index directly by using the 'range' function in the 'for' loop. This will give you a sequence of numbers that you can use as the indices of the iterable.
For example:
names = ['Alice', 'Bob', 'Charlie', 'Dave']
for i in range(len(names)):
print(f'{i}: {names[i]}')
This will also print out the following:
0: Alice 1: Bob 2: Charlie 3: Dave