Pythonic way to iterate through a range starting at 1

From the documentation:

range([start], stop[, step])

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.

e.g.

>>> for i in range(1, 7, 1): print(i)
... 
1
2
3
4
5
6
>>> for i in range(1, 7, 2): print(i)
... 
1
3
5

A nice feature, is that it works in reverse as well.

>>> for i in range(7, 0, -1): print(i)
... 
7
6
5
4
3
2
1

If you aren’t using it as an index but for something that can have positive or negative values, it still comes in handy:

>>> for i in range(2, -3, -1): print(i)
... 
2
1
0
-1
-2
>>> for i in range(-2, 3, 1): print(i)
... 
-2
-1
0
1
2

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)