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.)
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:
As mentioned elsewhere, this is an interesting and possibly faster alternative:
import itertools
for _ in itertools.repeat(None, 3):
print 'hi'
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.)
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:
As mentioned elsewhere, this is an interesting and possibly faster alternative:
import itertools
for _ in itertools.repeat(None, 3):
print 'hi'