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?
Advertisement
Answer
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