Python range() Function | Range Python

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))
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

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))
Output: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

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))
Output: [5, 10, 15, 20, 25, 30, 35, 40, 45]

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)
Output: 0 1 2 3 4 5 6 7 8 9
for i in range(10):
    print('*')
Output: * * * * * * * * * *
s = 'Python'
for i in s:
    print(i)
Output: P
y
t
h
o
n
s = 'Python'
for i in range(len(s)):
    print(i, s[i])    
Output: 0 P
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)))
Output: [10, 9, 8, 7, 6]
print(list(range(6, 5, -2)))
Output: [6]

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