CAJE CAJE - 7 months ago 10
Python Question

Pythonic way to iterate through a range starting at 1

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:


  1. With the
    1
    at the start of the range.

  2. With the
    + 1
    at the end of the range.


Answer

range(1, n+1) is not considered duplication, but I can see that this might become a hassle if you were going to change 1 to another number.

This removes the duplication using a generator:

for _ in (number+1 for number in range(5)):
    print(_)
Comments