Python Range Function
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|
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.
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.
If You Appreciate This, You Can Consider:
About The Author
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.