CAJE CAJE - 1 year ago 27
Python Question

Pythonic way to iterate through a range starting at 1

Currently if I want to iterate

I would likely use the following method:

for _ in range(1, n+1):

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
    at the start of the range.

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


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)):