Python range() is a built-in function that returns or generates an immutable sequence of numbers, starting from the lower bound to the upper bound.
Depending on the set of parameters Python range()
has two forms.
range(stop)
range(start,stop[,step])
ValueError
is raised>>> range(0)
range(0, 0)
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(1,10))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> #including step size
>>> list(range(1,15,3))
[1, 4, 7, 10, 13]
>>> #using 0 step size
>>> range(1,5,0)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
range(1,5,0)
ValueError: range() arg 3 must not be zero
As you can see, range()
in Python 3.x returns range or sequence and converting to list will show the list of range.
And also range()
raises ValueError
when 0
is supplied as step size.
>>> list(range(1,-15,-3))
[1, -2, -5, -8, -11, -14]
>>> #for loop with single parameter
>>> for i in range(4):
print(i)
0
1
2
3
>>> #for loop with step size
>>> for i in range(1,9,2):
print(i)
1
3
5
7