Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to iterate through a range starting at 1

Tags:

python

loops

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.
like image 962
CAJE Avatar asked Oct 22 '15 13:10

CAJE


People also ask

How do you make a range start at 1?

Note: Here, start = 0 and step = 1 as a default value. If you set the stop as a 0 or some negative value, then the range will return an empty sequence. If you want to start the range at 1 use range(1, 10) .

What is the correct way to iterate over a range of numbers?

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

How do you use the range in a for loop?

for loops repeat a block of code for all of the values in a list, array, string, or range() . We can use a range() to simplify writing a for loop. The stop value of the range() must be specified, but we can also modify the start ing value and the step between integers in the range() .

Does range in Python start at 0 or 1?

range() (and Python in general) is 0-index based, meaning list indexes start at 0, not 1. eg. The syntax to access the first element of a list is mylist[0] . Therefore the last integer generated by range() is up to, but not including, stop .


1 Answers

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 
like image 117
Rolf of Saxony Avatar answered Sep 24 '22 12:09

Rolf of Saxony