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') 
1
  • You make a good point! It was a frustratingly hard thing to search for. Commented Jun 18, 2011 at 17:08

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

6 Comments

@Dean: Your question illustrates why you should never use this variable name :)
@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.
@Dean Take a look at this question: link
@Dean: It is not special, it is a valid identifier
@Dean, there is nothing special about '_', but it is a common convention in Python to use it in this manner for throwaway variables.
|
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.

1 Comment

+1 for mentioning possible gettext conflict
4

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

Comments

3

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

Comments

2

Yes:

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

But you should prefer the for loop for readability

1 Comment

It didn't click, but print('Hello\n' * 10, end='') would also work. Good thinking :)
2

Try this little arabesqsue.

print "Hello\n"*10 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.