1

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.)

0

2 Answers 2

3

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

import itertools

for _ in itertools.repeat(None, 3):
    print 'hi'
Sign up to request clarification or add additional context in comments.

Comments

2

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:

4 Comments

Oh hey, there was a question already - didn't see that (And I did look!)
Additional question: The scope of the ' _ ' is for that loop, presumably - what if I need to do nested loops, will using ' _ ' in the internal loop mess it up for the external loop?
You shouldn't use the same variable name inside nested loops, take a look: stackoverflow.com/questions/13255455/…. Turn on your imagination in that case :)
for loopOne in range(0, 3) for loopTwo in range(0, 5)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.