The range() function in Python prints out a string of numbers according to the start value, end value, and jump we entered. In Python2 version, it is called xrange() function, it wasn’t until Python3 version that it was named range() function.
Here at LinuxAPT, as part of our Server Management Services, we regularly perform related Python functions queries.
In this context, we shall look into how to use the range() function in Python.
The range() function in Python prints out a string of numbers. By default, it will start at 0, step is 1 and stop at the specified number. We can specify starting point and step.
It's syntax is given below:
range(start, stop, step)
range() function Parameter Values:
1. Number sequence from 1 to 4
x = range(1, 5)
for i in x:
print(i)
It's Output is:
1
2
3
4
2. The sequence of numbers from 3 to 12 step is 3:
x = range(3, 15, 3)
for i in x:
print(i)
It's Output will be:
3
6
9
12
3. If you have function like this:
range() combined with the list() function
# Number range from 0 to 9
x = list(range(10))
print(x)
# Number range from 1 to 9
y = list(range(1,10))
print(y)
The Output will be:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
4. Sequence of even numbers from 2 to 12:
x = list(range(2,14,2))
print(x)
The Output will be:
[2, 4, 6, 8, 10, 12]
This article covers how to use the range() function in Python via examples. In fact, The range() function is used to generate a sequence of numbers over time. At its simplest, it accepts an integer and returns a range object (a type of iterable). In Python 2, the range() returns a list which is not very efficient to handle large data.