fightstarr20
fightstarr20

Reputation: 12608

Python run code every 100th loop item

I have this simple loop in Python that I am using..

for i, numbercode in enumerate(numbercode_list):
    print ("Item : %s" %i )
    driver.close()
    driver = init_driver()

How would I go about just running the last two lines every 100th loop item? Currently it runs them every time.

Upvotes: 7

Views: 14453

Answers (3)

Mathias711
Mathias711

Reputation: 6668

You can also do something more Pythonic:

for i in range(1000)[::100]:
    if i%100==0:
        print i

The [::100] takes every 100-th item of your list. So this assumes numbercode_list is a list or array.

Upvotes: 1

mfitzp
mfitzp

Reputation: 15545

You can take the modulus of the number and compare to zero. Modulo (% in Python) yields the remainder from the division of the first argument by the second, e.g.

>>> 101 % 100
1

>>> 100 % 100
0

For your example, this could be applied as follows:

for i, numbercode in enumerate(numbercode_list):
    print ("Item : %s" %i )
    if i % 100 == 0:
        driver.close()
        driver = init_driver()

Upvotes: 11

tfv
tfv

Reputation: 6259

Why not use the modulo operation?

for i in range(1000):
    if i%100==0:
        print i

Edit: Sorry, too slow

Upvotes: 2

Related Questions