Python ForLoop syntax

Question:

This works:

for i in range(0, 3):
    print "hi"

This doesn’t work:

for range(0, 3):
    print "hi"

but I don’t need the ‘i’ for anything at all. Is there a way to write a ‘for’ statement without the ‘i’ or a different character which assumes the same role?

( Typically, it would be something like

for i in range(0, someReturnValue())
    someFunction()

but the question is generalizable to my first examples.)

Asked By: shieldfoss

||

Answers:

If you don’t need a lopping variable(index), the best practice is to use _ (which is, really, just another variable):

for _ in range(0, 3):
    print "hi"

Also see:

Answered By: alecxe

As mentioned elsewhere, this is an interesting and possibly faster alternative:

import itertools

for _ in itertools.repeat(None, 3):
    print 'hi'
Answered By: C Mars
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.