Python Range Function By Dhiraj,   16 March, 2019 0K

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.

Range Construction

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.

Constructor Arguments Result
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

Rules to Define Range

• The arguments to the range constructor must be integers.
• Default value of step argument is 0.
• The stop value in the range() constructor is one-past-the-end.
• If step is zero, ValueError is raised.
• Iteration over range is always faster then other collection types such as list, tuple as range object always only stores the start, stop and step values.

Range Examples

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)

Conclusion

In this article, we learnt about range() function in Python with simple examples.

If You Appreciate This, You Can Consider: I am an energetic professional who enjoys the challenges involved in working with people and resolving real-time problems. Technical expertise in building highly scalable, distributed and self-healing cloud applications. Technical Skills: Java/J2EE, Spring Framework, Hibernate, Angular, Reactive Programming, Microservices, Rest APIs, Kafka, ELK, etc.

Further Reading on Python

1 Python Data Types

2 Introduction To Python

3 Different Python Operators

4 Python Flow Control

5 Python Functions

6 Variable Assignment In Python

7 Exception Handling In Python

8 Python Classes