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
at the start of the range.+ 1
at the end of the range.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) .
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.
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() .
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 .
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With