Skip to main content
HomeAbout PythonLearn Python

Python Range() Function Tutorial

Learn about the Python Range() function and its capabilities with the help of examples.
Mar 2020  · 7 min read

If you are just getting started in Python and would like to learn more, take DataCamp's Introduction to Data Science in Python course.

In today's tutorial, you will be learning about a built-in Python function called range() function. It is a very popular and widely used function in Python, especially when you are working with predominantly for loops and sometimes with while loops. It returns a sequence of numbers and is immutable (whose value is fixed). The range function takes one or at most three arguments, namely the start and a stop value along with a step size.

Range function was introduced only in Python3, while in Python2, a similar function xrange() was used, and it used to return a generator object and consumed less memory. The range() function, on the other hand, returns a list or sequence of numbers and consumes more memory than xrange().

Since the range() function only stores the start, stop, and step values, it consumes less amount of memory irrespective of the range it represents when compared to a list or tuple.

The range() function can be represented in three different ways, or you can think of them as three range parameters:

  • range(stop_value) : This by default considers the starting point as zero.
  • range(start_value, stop_value) : This generates the sequence based on the start and stop value.
  • range(start_value, stop_value, step_size): It generates the sequence by incrementing the start value using the step size until it reaches the stop value.
range function

Let's first check the type of the range() function.


Let's start with a simple example of printing a sequence of ten numbers, which will cover your first range parameter.

  • To achieve this, you will be just passing in the stop value. Since Python works on zero-based indexing, hence, the sequence will start with zero and stop at the specified number, i.e., $n-1$, where $n$ is the specified number in the range function.
range(10) #it should return a lower and an upper bound value.
range(0, 10)
for seq in range(10):

As expected, the above cell returns a sequence of numbers starting with $0$ and ending at $9$.

You could also use the range function as an argument to a list in which case it would result in a list of numbers with a length equal to the stop value as shown below:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • Next, let's look at the second way of working with the range function. Here you will specify both start and the stop value.
range(5, 10)
for seq in range(5,10):

Similarly, you can use the range function to print the negative integer values as well.

for seq in range(-5,0):
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
  • Let's now add the third parameter, i.e., the step size to the range function, and find out how it affects the output. You will specify the start point as 50, the end/stop value as 1000 with a step size of 100. The below range function should output a sequence starting from 50 incrementing with a step of 100.
range(50, 1000, 100)

You will notice that it will print all even numbers.

for seq in range(50,1000,100):

It is important to note that the range() function can only work when the specified value is an integer or a whole number. It does not support the float data type and the string data type. However, you can pass in both positive and negative integer values to it.

Let's see what happens when you try to pass float values.

for seq in range(0.2,2.4):

TypeError                                 Traceback (most recent call last)

<ipython-input-32-4d2f304928d0> in <module>
----> 1 for seq in range(0.2,2.4):
      2     print(seq)

TypeError: 'float' object cannot be interpreted as an integer
  • You would have scratched your head at least once while trying to reverse a linked list of integer values in C language. However, in python, it can be achieved with the range function with just interchanging the start and stop along with adding a negative step size.

    Isn't that so simple? Let's find out!

for seq in range(100,10,-10):

Say you have a list of integer values, and you would like to find the sum of the list, but using the range() function. Let's find out it can be done.

First, you will define the list consisting of integer values. Then initialize a counter in which you will store the value each time you iterate over the list and also add the current list value with the old count value.

To access the elements from the list, you will apply the range function on the length of the list and then access the list elements bypassing the index i which will start from zero and stop at the length of the list.

list1 = [2,4,6,8,10,12,14,16,18,20]
count = 0

for i in range(len(list1)):
    count = count + list1[i]
print('sum of the list:', count)
sum of the list: 110

You could also concatenate two or more range functions using the itertools package class called chain. And not just the range function, you could even concatenate list, tuples, etc. Remember that chain method returns a generator object, and to access the elements from that generator object, you can either use a for loop or use list and pass the generator object as an argument to it.

from itertools import chain

a1 = range(10,0,-2)
a2 = range(30,20,-2)
a3 = range(50,40,-2)

final = chain(a1,a2,a3)

print(final) #generator object
<itertools.chain object at 0x107155490>
[10, 8, 6, 4, 2, 30, 28, 26, 24, 22, 50, 48, 46, 44, 42]

You can apply equality comparisons between range functions. Given two range functions, if they represent the same sequence of values, then they are considered to be equal. Having said that, two equal range functions don't need to have the same start, stop, and step attributes.

Let's understand it with an example.

list(range(0, 10, 3))
[0, 3, 6, 9]
list(range(0, 11, 3))
[0, 3, 6, 9]
range(0, 10, 3) == range(0, 11, 3)
range(0, 10, 3) == range(0, 11, 2)

As you can observe from the above outputs, even though the parameters of the range function are different, they are still considered to be equal since the sequence of both the functions is the same. While in the second example, changing the step size makes the comparison False.


Congratulations on finishing the tutorial.

You might want to tinker around a bit with the Range function and find out a way to customize it for accepting data types other than just integers.

Please feel free to ask any questions related to this tutorial in the comments section below.

Check out DataCamp's Python Functions Tutorial.

If you would like to learn more, take a look at the following DataCamp courses:

Learn more about Python

Certification available

Writing Functions in Python

BeginnerSkill Level
4 hr
Learn to use best practices to write maintainable, reusable, complex functions with good documentation.
See DetailsRight Arrow
Start Course
See MoreRight Arrow

10 Essential Python Skills All Data Scientists Should Master

All data scientists need expertise in Python, but which skills are the most important for them to master? Find out the ten most vital Python skills in the latest rundown.

Thaylise Nakamoto

9 min

The 7 Best Python Certifications For All Levels

Find out whether a Python certification is right for you, what the best options are, and the alternatives on offer in this comprehensive guide.
Matt Crabtree's photo

Matt Crabtree

18 min

A Complete Guide to Socket Programming in Python

Learn the fundamentals of socket programming in Python
Serhii Orlivskyi's photo

Serhii Orlivskyi

41 min

Textacy: An Introduction to Text Data Cleaning and Normalization in Python

Discover how Textacy, a Python library, simplifies text data preprocessing for machine learning. Learn about its unique features like character normalization and data masking, and see how it compares to other libraries like NLTK and spaCy.

Mustafa El-Dalil

5 min

Coding Best Practices and Guidelines for Better Code

Learn coding best practices to improve your programming skills. Explore coding guidelines for collaboration, code structure, efficiency, and more.
Amberle McKee's photo

Amberle McKee

26 min

Pandas Profiling (ydata-profiling) in Python: A Guide for Beginners

Learn how to use the ydata-profiling library in Python to generate detailed reports for datasets with many features.
Satyam Tripathi's photo

Satyam Tripathi

9 min

See MoreSee More