syntax is range(start, end, step). Example: range(0,100,10).
Here's the output as a list, using list(range(0,100,10))
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
If you want it to reach 100, with stepsize=10, then add that to your range end, list(range(0,110,10)) gives
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Videos
Say for example I have this code:
n = 10
i = 2
for j in range(i*i, n, i):
print(j)
I see in my editor this prints: 4,6,8
My question is what is happening inside of range(i*i, n, i)?Does every iteration tack on +1?Like this:
for j in range(2*2, 10, 2) for j in range(2*3, 10, 2) for j in range(2*4, 10, 2)
But doesn't the step=2 ensure that it goes up in by steps of 2 each time like so:
for j in range(2*2, 10, 2) for j in range(2*4, 10, 2) for j in range(2*6, 10, 2)
Im confused on how the step part actually works.
Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result.
Use the linspace function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain). linspace takes a number of points to return, and also lets you specify whether or not to include the right endpoint:
>>> np.linspace(0,1,11)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
If you really want to use a floating-point step value, use numpy.arange:
>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
Floating-point rounding error will cause problems, though. Here's a simple case where rounding error causes arange to produce a length-4 array when it should only produce 3 numbers:
>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])
range() can only do integers, not floating point.
Use a list comprehension instead to obtain a list of steps:
[x * 0.1 for x in range(0, 10)]
More generally, a generator comprehension minimizes memory allocations:
xs = (x * 0.1 for x in range(0, 10))
for x in xs:
print(x)