Appearance
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:
Accessing the index in a for loop over an enum in Python
python
names = ['Alice', 'Bob', 'Charlie', 'Dave']
for i, name in enumerate(names):
print(f'{i}: {name}')This will print out the following:
enumerate output
console
0: Alice
1: Bob
2: Charlie
3: DaveYou 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:
Accessing the index in a for loop over the integer range of an array length in Python
python
names = ['Alice', 'Bob', 'Charlie', 'Dave']
for i in range(len(names)):
print(f'{i}: {names[i]}')This will also print out the following:
for in range output
console
0: Alice
1: Bob
2: Charlie
3: Dave