'Get the number of runs in a for loop
I have a simple loop, which has a step of 5. How can I get the index of the iteration of the loop? I know that we can derive this index using division, but I need those indices in the loop.
For a simple loop like the following, I want to print the list:
for i in range(0, 20, 5):
print(' ')
out = [0, 1, 2, 3]
Solution 1:[1]
You can use enumerate():
out = []
for counter, idx in enumerate(range(0, 20, 5)):
print(idx)
out.append(counter)
print(out)
This outputs:
0
5
10
15
[0, 1, 2, 3]
Solution 2:[2]
you can use:
for index,i in enumerate(range(0, 20, 5)):
print(f'{i}')
print(f'{index}')
Solution 3:[3]
I think there are two methods:
- standard:
c = []
for i in range(0, 20, 5):
c.append(len(c));
print(c);
[0, 1, 2, 3]
- optimized:
a = list(range(0, 20, 5))
print(a)
[0, 5, 10, 15]
b = [i for i in range(0, len(a))]
print(b)
[0, 1, 2, 3]
Thank you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrokenBenchmark |
| Solution 2 | Mr T |
| Solution 3 |
