Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to iterate a specified number of times without introducing an unnecessary variable?

If I want to iterate n times in Java, I write:

for (i = 0; i < n; i++) {
    // do stuff
}

In Python, it seems the standard way to do this is:

for x in range(n):
    # do stuff

As always, Python is more concise and more readable. But the x bothers me, as it is unnecessary, and PyDev generates a warning, since x is never used.

Is there a way to do this that doesn't generate any warnings, and doesn't introduce unnecessary variables?

like image 421
Eric Wilson Avatar asked Aug 19 '10 16:08

Eric Wilson


1 Answers

Idiomatic Python (and many other languages) would have you use _ as the temporary variable, which generally indicates to readers that the variable is intentionally unused.

Aside from that convention, the in loop-construct in Python always requires you to iterate over something and assign that value to a variable.

(The comments in the accepted answer of this question suggest that PyDev won't create a warning for _).

for _ in range(n):
    # do stuff
like image 159
Mark Rushakoff Avatar answered Oct 05 '22 06:10

Mark Rushakoff