开发者

Iterate a certain number of times without storing the iteration number anywhere [duplicate]

This question already has answers here: 开发者_StackOverflow社区 Is it possible to implement a Python for range loop without an iterator variable? (15 answers) Closed 4 years ago.

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?

Needless to say, using a variable is not a big deal at all... I'm just curious.


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


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"


Well I think the forloop you've provided in the question is about as good as it gets, but I want to point out that unused variables that have to be assigned can be assigned to the variable named _, a convention for "discarding" the value assigned. Though the _ reference will hold the value you gave it, code linters and other developers will understand you aren't using that reference. So here's an example:

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


Others have addressed the inability to completely avoid an iteration variable in a for loop, but there are options to reduce the work a tiny amount. range has to generate a whole bunch of numbers after all, which involves a tiny amount of work; if you want to avoid even that, you can use itertools.repeat to just get the same (ignored) value back over and over, which involves no creation/retrieval of different objects:

from itertools import repeat

for _ in repeat(None, 200):  # Runs the loop 200 times
    ...

This will run faster in microbenchmarks than for _ in range(200):, but if the loop body does meaningful work, it's a drop in the bucket. And unlike multiplying some anonymous sequence for your loop iterable, repeat has only a trivial setup cost, with no memory overhead dependent on length.


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


This will print 'hello' 3 times without storing i...

[print('hello') for i in range(3)]


Sorry, but in order to iterate over anything in any language, Python and English included, an index must be stored. Be it in a variable or not. Finding a way to obscure the fact that python is internally tracking the for loop won't change the fact that it is. I'd recommend just leaving it as is.


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

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


You can simply do

print 2*'hello'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜