In this tutorial, we will learn about Range() in Python and will see some of its uses.
The Python range() function is used to return a sequence of numbers starting from 0 (by default if starting position is not provided) to the specified number by incrementing 1 (by default if increment value is not provided.) Let’s see it in detail.
Syntax of the range() function
range(start, stop, step)
Here start is an optional value that you may specify to start the sequence from. The Stop value is necessary where your sequence stops. and finally, the step is the increment value which you may provide optionally for incrementing steps.
If you don’t provide the start value, by default the sequence starts from 0, similarly, if you don’t provide the step value, it increment by 1 by default.
One thing to note is that the sequence stops one step before the stop value. Let’s see all these from examples:
sequence = range(10)
print(list(sequence))
As we can see from the above result since we haven’t provided the start and step value, the sequence started from 0 and incremented by 1 at every step. Also, the sequence stopped one step before the step value.
sequence = range(5, 15)
print(list(sequence))
Here we can see the sequence has started from 5 since we have provided the start value.
sequence = range(5, 50, 5)
print(list(sequence))
In the above example, we have provided the start and step values, so the counting started from 5 and incremented by 5 at every step.
Some more examples of Python Range() function
for i in range(10):
print(i)
for i in range(10):
print('*')
s = 'Python'
for i in s:
print(i)
y
t
h
o
n
s = 'Python'
for i in range(len(s)):
print(i, s[i])
1 y
2 t
3 h
4 o
5 n
What if the start value is greater than the stop value? Let’s see:
print(list(range(10, 5, -1)))
print(list(range(6, 5, -2)))
Try Python basics on our Online Python Compiler
Related:
Python Basics
List, Set, Tuple, and Dictionary in Python
Python Reverse List items
Python Round() Function
Python Multiline comment
Power in Python | Python pow()
Python range() Function
Square Root in Python
Python for i in range
Python Exception Handling