Currently if I want to iterate 1
through n
I would likely use the following method:
for _ in range(1, n+1):
print(_)
Is there a cleaner way to accomplish this without having to reference n + 1
?
It seems odd that if I want to iterate a range ordinally starting at 1, which is not uncommon, that I have to specify the increase by one twice:
- With the
1
at the start of the range. - With the
+ 1
at the end of the range.
This will output:
range(1, n+1)
is not considered duplication, but I can see that this might become a hassle if you were going to change1
to another number.This removes the duplication using a generator:
range(1, n+1)
is common way to do it, but if you don't like it, you can create your function:From the documentation:
The start defaults to 0, the step can be whatever you want, except 0 and stop is your upper bound, it is not the number of iterations. So declare n to be whatever your upper bound is correctly and you will not have to add 1 to it.
Not a general answer, but for very small ranges (say, up to five), I find it much more readable to spell them out in a literal:
That's true even if it does start from zero.