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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
shieldfoss
  • 886
  • 2
  • 12
  • 22

2 Answers2

3

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

import itertools

for _ in itertools.repeat(None, 3):
    print 'hi'
C Mars
  • 2,909
  • 4
  • 21
  • 30
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:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Oh hey, there was a question already - didn't see that (And I did look!) – shieldfoss Jul 30 '13 at 08:46
  • 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? – shieldfoss Jul 30 '13 at 09:03
  • You shouldn't use the same variable name inside nested loops, take a look: http://stackoverflow.com/questions/13255455/same-variable-name-for-different-values-in-nested-loops. Turn on your imagination in that case :) – alecxe Jul 30 '13 at 09:15
  • for loopOne in range(0, 3) for loopTwo in range(0, 5) – shieldfoss Jul 30 '13 at 09:52