Range in Python is a collection that represents an arithmetic progression of integers. In this tutorial, we will learn about
range() in detail and take a look into different use cases of this function with examples.
The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops. Range is created by calling
range() constructor and there is no literal form. Mostly, range is used to create integers for loop counters. Below are the different constructors that can be used to create Range object.
|range(5)||stop||0, 1, 2, 3, 4|
|range(5, 10)||start, stop||5, 6, 7, 8, 9|
|range(10, 20, 2)||start, stop, step||10, 12, 14, 16, 18|
Print a sequence from 1 to 5.
for i in range(5): print(i)
print(list(range(10))) #List of numbers to 10, start with 0 by default print(list(range(1, 10))) #List of numbers from start index 1 to 10 print(list(range(0, 10, 3))) #List of numbers from start index 0 to 10 with step value 3
Avoid range() for iterating over lists. Below is a wrong practise in Python.
x = [1, 2, 3] for i in range(len(x)): print(x[i])
Instead, use direct iteration over iterables.
x = [1, 2, 3] for i in x: print(i)
In this article, we learnt about range() function in Python with simple examples.