In this article are covered several examples of range function:
- basic use
- range by step
- range start and end limit
- python range next
- accessing range elements
- negative numbers
- python range decrease
Basic use of range
Basic usage of range function in Python is:
for i in range(7):
print (i)
this is equivalent to:
for i in [0,1,2,3,4,5,6]:
print (i)
result:
0, 1, 2, 3, 4, 5, 6,
by step
Note that if you give only 1 parameter than this is the upper limit starting from 0. So if you use -7 nothing will be produced:
for i in range(-7):
print(i, end=', ')
Range with start and end
You can define the start and end of the range by giving two parameters.:
for i in range(2,7):
print(i, end=', ')
result:
2, 3, 4, 5, 6,
Note that upper limit should be bigger otherwise nothing will be produced.
for i in range(7,2):
print(i, end=', ')
Range by step
Adding third parameter will define the step of the range. So you can get all even or odd numbers. Or get all numbers from 0..100 which divide to 5:
for i in range(0, 100, 5):
print (i, end=', ')
result:
0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95,
Python range negative numbers
If you want to work with negative numbers than you have to use negative limits:
for i in range(-10, 0, 2):
print (i, end=', ')
result:
-10, -8, -6, -4, -2,
Python range decrease
You can work with range in decreasing order by using negative step:
for i in range(10, 0, -2):
print (i, end=', ')
result:
10, 8, 6, 4, 2,
Working with python range, check start, stop and step
You can create and assign range to python variable:
range5 = range(5, 100, 20)
print (range5)
print(range5.step)
print(range5.start)
print(range5.stop)
result:
range(5, 100, 20)
20
5
100
Check if value is in range
You can work with range in decreasing order by using negative step:
range5 = range(5, 100, 20)
print(5 in range(10))
print(5 in range5)
print(15 in range5)
result:
True
True
False
Access range elements
Ranges can be considered in some ways as a python lazy lists and the access can be done in similar way:
range5 = range(5, 100, 20)
print(range(0,10,3)[3])
print (range5[3])
result:
9, 65
Python range next
If you want to get the next value of range object then you have to use iter and then call function next on it:
range5 = range(5, 100, 20)
it = iter(range5)
print(next(it))
print(next(it))
result:
5, 25