Search code examples
pythonloopsanti-patterns

Most Pythonic Way to Run a Process X Times


Which is more pythonic?

While loop:

count = 0
while count < 50:
    print "Some thing"
    count = count + 1

For loop:

for i in range(50):
    print "Some thing"

Edit: not duplicate because this has answers to determine which is clearer, vs. how to run a range without 'i' -- even though that ended up being the most elegant


Solution

  • Personally:

    for _ in range(50):
        print "Some thing"
    

    if you don't need i. If you use Python < 3 and you want to repeat the loop a lot of times, use xrange as there is no need to generate the whole list beforehand.