Iterate a certain number of times without storing the iteration number anywhere

BorrajaX picture BorrajaX · Sep 10, 2010 · Viewed 131.7k times · Source

I was wondering if it is possible to perform a certain number of operations without storing the loop iteration number anywhere.

For instance, let's say I want to print two "hello" messages to the console. Right now I know I can do:

for i in range(2):
    print "hello"

but then the i variable is going to take the values 0 and 1 (which I don't really need). Is there a way to achieve the same thing without storing those unwanted values anywhere?

Answer

user395760 picture user395760 · Sep 10, 2010

The idiom (shared by quite a few other languages) for an unused variable is a single underscore _. Code analysers typically won't complain about _ being unused, and programmers will instantly know it's a shortcut for i_dont_care_wtf_you_put_here. There is no way to iterate without having an item variable - as the Zen of Python puts it, "special cases aren't special enough to break the rules".