Sadcow
Sadcow

Reputation: 730

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]

Upvotes: 1

Views: 777

Answers (3)

Massi FD
Massi FD

Reputation: 398

I think there are two methods:

  1. standard:
    c = []
    for i in range(0, 20, 5):
        c.append(len(c));
    print(c);
    [0, 1, 2, 3]
  1. 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

Upvotes: 0

Mr T
Mr T

Reputation: 73

you can use:

for index,i in enumerate(range(0, 20, 5)):
    print(f'{i}')
    print(f'{index}')

Upvotes: 1

BrokenBenchmark
BrokenBenchmark

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

Related Questions