Python - When to use Ranges
When to use Ranges in Python
You can use Ranges in Python where you need to iterate over a sequence of numbers, or perform a repetitive task a specific number of times.
In the following, we have covered some most used scenarios where Ranges are used.
1. Iterate over a sequence of numbers
In the following example, we use range() function with For loop to iterate over a sequence of numbers.
Python Program
my_range = range(9)
for i in my_range:
print(i)
Output
0
1
2
3
4
5
6
7
8
2. Access elements in a list within a specific range of indices
In the following example, we use range() function to access elements in the list my_list in the index range of [4,9).
Python Program
my_list = [2 , 5 , 2 , 0, 8, 7, 3, 0, 2, 4, 5, 7, 8]
for i in range(4, 9):
print(my_list[i])
Output
8
7
3
0
2
3. Generate Sequences using range()
You can use Ranges to generate a sequence of numbers that can be stored in a list or used for other purposes.
In the following example, we use range() function to generate a sequence of numbers from 10 until 100 with a step value of 50 and store this sequence in a list my_list.
Python Program
my_range = range(10, 1000, 50)
my_list = list(my_range)
print(my_list)
Output
[10, 60, 110, 160, 210, 260, 310, 360, 410, 460, 510, 560, 610, 660, 710, 760, 810, 860, 910, 960]
4. Control For loop iterations
Generally For loop is used to iterate over a collection of items. But, with range(), we can execute For loop for desired number of iterations.
In the following example, we use range() function to iterate the For loop for 5 times.
Python Program
for i in range(5):
print('Hello World')
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Summary
In this tutorial of Python Ranges, we learned when to use Python Ranges in a program.