views:

96

answers:

4

Hello...

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 on 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 that anywhere?

I know it's not big deal... I'm just curious :-)

Thank you in advance

+9  A: 

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

delnan
A: 
for word in ['hello'] * 2:
    print word

It's not idiomatic Python, but neither is what you're trying to do.

Nathon
For example, you need an unused variable to generate a list of random numbers.
wRAR
The thing is, the variable isn't actually unused. Somebody has to keep track of how many times to iterate, and how many times the loop has been executed.
Nathon
@Nathon: Wrong. Since `for i in seq: stuff()` is equivalent to (forgive me the braces, but comments don't preverve newlines) `_iterator = iter(seq); while True { try { i = next(_iterator) } except StopIteration { break } stuff() }`, we could remove the `i = ` part from the desugared version and end up with no iteration variable. All iteration state is managed by the iterator, not by the iteration variable.
delnan
@delnan I meant down in the guts. The implementation still needs to keep track (even if it's hiding somewhere in an iterator class). There will always be some memory somewhere devoted to keeping track of where in the iteration we are. It may be inaccessible, but that doesn't make it not exist.
Nathon
+1  A: 
exec 'print "hello";' * 2

should work, but I'm kind of ashamed that I thought of it.

Update: Just thought of another one:

for _ in " "*10: print "hello"
recursive
+1  A: 

Although I agree completely with delnan's answer, it's not impossible:

loop = range(NUM_ITERATIONS+1)
while loop.pop():
    do_stuff()

Note, however, that this will not work for an arbitrary list: If the first value in the list (the last one popped) does not evaluate to False, you will get another iteration and an exception on the next pass: IndexError: pop from empty list. Also, your list (loop) will be empty after the loop.

Just for curiosity's sake. ;)

Walter