The pythonic way of iterating in the range of 1

Currently, if I want to iterate 1 through n , I would use the following method:

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

Is there a cleaner way to do this without referencing n + 1 ?

It seems strange that if I want to iterate over a range starting from 1, which is not unusual, I have to specify a double increase:

  • With 1 at the beginning of the range.
  • C + 1 at the end of the range.
+5
source share
5 answers

range(1, n+1) not considered duplication, but I see that this can be a problem if you are going to change 1 to another number.

This removes duplication using a generator:

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

range(1, n+1) is the usual way to do this, but if you don't like it, you can create your own function:

 def numbers(first_number, last_number, step=1): return range(first_number, last_number+1, step) for _ in numbers(1, 5): print(_) 
+1
source

From the documentation:

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

The default start is 0, the step can be anything but 0, and stop is your upper bound, this is not the number of iterations. Thus, we declare that n is that your upper bound is correct, and you will not need to add 1 to it.

+1
source

Not a general answer, but for very small ranges (say, up to five), I find it more readable to write them down literally:

 for _ in [1,2,3]: print _ 

This is true even if it starts from scratch.

+1
source
 for i in range(n): print(i+1) 

This will output:

 1 2 ... n 
0
source

Source: https://habr.com/ru/post/1234274/


All Articles