4

Possible Duplicate:
how can i get around declaring an unused variable in a for loop

In Python, particularly with a for-loop, is there a way to not create a variable if you don't care about it, ie the i in this example which isn't needed:

for i in range(10):
    print('Hello')
Community
  • 1
  • 1
Dean Barnes
  • 2,252
  • 4
  • 29
  • 53

6 Answers6

8

No, but often you will find that _ is used instead:

for _ in range(10):
    print('Hello')

You only have to be careful when you use gettext.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Does the _ have a particular meaning, or is it actually for this purpose? – Dean Barnes Jun 18 '11 at 16:55
  • 2
    @Dean: Your question illustrates why you should never use this variable name :) – Sven Marnach Jun 18 '11 at 16:57
  • 1
    @Dean Barnes It has no particular meaning. Since `_` is also a magic variable in the interactive shell (always contains the result of the last expression), it's well-suited as a dummy variabnle. – phihag Jun 18 '11 at 16:57
  • 1
    @Dean Take a look at this question: [link](http://stackoverflow.com/questions/1538832/is-this-single-underscore-a-built-in-variable-in-python) – K4emic Jun 18 '11 at 16:58
  • 1
    @Dean: It is not special, it is a valid [identifier](http://docs.python.org/reference/lexical_analysis.html#identifiers) – Felix Kling Jun 18 '11 at 16:59
  • 1
    @Dean, there is nothing special about '_', but it is a common convention in Python to use it in this manner for throwaway variables. – Corey Goldberg Jun 18 '11 at 17:17
5

A for-loop always creates a name. If you don't want to use it, just make this clear by its name, for example call it dummy. Some people also use the name _ for an unused variable, but I wouldn't recommend this name because it tends to confuse people, making them think this is some special kind of syntax. Furthermore, it clashes with the name _ in the interactive interpreter and with the common gettext alias of the same name.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
4

I've seen people use _ as a throw-away variable. I tend to just use i and not use it.

Zach Kelling
  • 52,505
  • 13
  • 109
  • 108
3

Just use a variable name you don't care about. This could be dummy or the often-seen _.

phihag
  • 278,196
  • 72
  • 453
  • 469
2

Yes:

from __future__ import print_function
print(*['Hello']*10, sep='\n')

But you should prefer the for loop for readability

JBernardo
  • 32,262
  • 10
  • 90
  • 115
2

Try this little arabesqsue.

print "Hello\n"*10
ncmathsadist
  • 4,684
  • 3
  • 29
  • 45