Reputation: 730
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]
Upvotes: 1
Views: 777
Reputation: 398
I think there are two methods:
c = []
for i in range(0, 20, 5):
c.append(len(c));
print(c);
[0, 1, 2, 3]
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
Upvotes: 0
Reputation: 73
you can use:
for index,i in enumerate(range(0, 20, 5)):
print(f'{i}')
print(f'{index}')
Upvotes: 1
Reputation: 19243
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]
Upvotes: 3