Python range() Function – Explained with Code Examples

Bala Priya C

In Python, can use use the range() function to get a sequence of indices to loop through an iterable. You’ll often use range() in conjunction with a for loop.
In this tutorial, you’ll learn about the different ways in which you can use the range() function – with explicit start and stop indices, custom step size, and negative step size.
Let’s get started.
Understanding Python’s range() Function
Before looking at the different ways of using the range() function, you’ve got to understand how it works.
As stated above, the range function does not return a list of indices. Rather, it returns a range object which returns the indices as and when you need them. This makes it memory-efficient as well.
You can use the range() function with the following general syntax:
When you use this syntax in conjunction with a loop, you can get a sequence of indices from start up to but not including stop , in steps of step .
- You must specify the required argument stop , which can be any positive integer. If you specify a floating point number instead, you’ll run into a TypeError as shown:
- If you don’t specify the start index, the default start index of 0 is used.
- If you don’t specify the step value, the default step size of 1 is used.
In the subsequent sections, you’ll learn about the different ways of using the range() function.
How to Use Python’s range() Function to Loop Through Any Iterable
As mentioned in the previous section, you only need one positive integer to use the range() function. The syntax is shown below:
You can use the above line of code to get a sequence from 0 through stop-1 : 0 , 1 , 2 , 3 . stop-1 .
▶ Consider the following example where you call range() with 5 as the argument. And you loop through the returned range object using a for loop to get the indices 0,1,2,3,4 as expected.
If you remember, all iterables in Python follow zero-indexing. This is why it’s convenient to use range() to loop through iterables.
An iterable of length len has 0 , 1 , 2 , . len-1 as the valid indices. So to traverse any iterable, all you need to do is to set the stop value to be equal to len . The sequence you’ll get – 0 , 1 , 2 , . len-1 – is the sequence of valid indices.
▶ Let’s take a more helpful example. You have a list my_list . You can access all items in the list by knowing their indices, and you can get those indices using range() as shown below:
Remember, you can use Python’s built-in function len to get the length of any iterable. In the above code, you use both the valid indices, and the list items at those valid indices. Here’s the output:

Notice how my_list is 7 items long, and the indices obtained are from 0 through 6, as expected.
Sometimes, you may need to use negative integers instead. In this case, if you use only the stop argument, you’ll not get the desired output, though the code doesn’t throw an error.
This is because the default start value is assumed to be 0 , and you cannot count up from 0 to -5 .
How to Use Python’s range() Function with Explicit Start and End Indices
You may not always want to start at zero. You can start at any arbitrary index by setting the start value to the index that you’d like to start from. The syntax is as follows:
In this case, you’ll be able to get the sequence: start , start + 1 , start + 2 , and so on up to stop-1 .
▶ In the example below, you’re starting at 10, count all the way up to but not including 15 in steps of 1.
In the previous section, you saw how using only the stop argument won’t work when you need negative integers. However, when you specify start and stop indices explicitly, you can as well work with negative integers.
▶ In this example, you’re trying to count up from -5 in steps of 1. Always keep in mind that the counting stops at the value that’s one less than the stop index.
How to Use Python’s range() Function with a Custom Step Size
Instead of traversing an iterable sequentially, you may sometimes want to stride through it, accessing every k -th element. This is when the optional step argument comes in handy. The general syntax is shown below:
When you use this syntax and loop through the range object, you can go from start to stop-1 with strides of size step .
- You’ll get the sequence: start , start + step , start + 2*step , and so on up to start + k*step such that start + k*step < stop and start + (k+1)*step > stop .
▶ In the example below, you’d like to go from 0 to 20 in steps of 2. Notice how the last index printed out is 19. This is because, if you take another step, you’ll be at 21 which is greater than 20.
Always remember, the last value you get can be as close to stop as possible, but can never be stop .
How to Use Python’s range() Function with a Negative Step Size
So far, you’ve learned to use the range() function with start and stop indices, and a specific step size, all the while counting up from start to stop .
If you need to count down from an integer, you can specify a negative value for step . The general syntax is:
- The range object can now be used to return a sequence that counts down from start in steps of negative_step , up to but not including stop .
- The sequence returned is start , start — negative_step , start — 2*negative_step , and so on up to start — k*negative_step such that start — k*negative_step > stop and start — (k+1)*negative_step < stop .
- There’s no default value for negative step – you must set negative_step = -1 to count down covering each number.
▶ In this example, you’d like to count down from 20 in steps of -2. So the sequence is 20, 18, 16, all the way down to 2. If you go another 2 steps lower, you’ll hit 0, which you cannot as it’s smaller than the stop value of 1.
It’s easy to see that start > stop to be able to count down.
▶ In the above example, you try counting down from 10 to 20 which is impossible. And you don’t get any output which is expected.
How to Use Python’s range() and reversed() Functions to Reverse a Sequence
If you need to access the elements of an iterable in the reverse order, you can use the range() function coupled with the reversed() function.
▶ Let’s take our very first example, where we used range(5) . In the example below, we call reversed() on the range object. And we see that we’ve counted down from 4 to 0.
As you can see, this is equivalent to using range(4,-1,-1) . If you prefer, you may use the reversed() function instead of negative_step argument discussed in the previous section.
Conclusion
In this tutorial, you’ve learned the different ways in which you can use the range() function. You can try a few examples to get a different sequence each time. This practice will help you use range() effectively when looping through iterables.
Python range() Function: How-To Tutorial With Examples
The Python range() function can be used to create sequences of numbers. The range() function can be iterated and is ideal in combination with for-loops. This article will closely examine the Python range function:
- What it is?
- How to use range()
- How to create for-loops with the range() function
I’ll also show you how to use ranges in for-loops to create any kind of loop you want, including:
- Regular loops over an increasing range of numbers
- Loops that go backward (e.g. from 10 to 0)
- Loops that skip values
Table of Contents
What is the Python range function?
Python’s range acts as a built-in function, and is commonly used for looping a specific number of times in for-loops. Like many things in Python, it’s actually a Python type (or class), but when using it in a loop, we can treat it like a built-in function that returns an iterable object.
Range offers us a calculated sequence of numbers based on our input. There are three ways to call the range function:
The arguments start, stop, and step are always integers. When we call range, it returns an object of class range . This range object can in turn provide a Python iterator, meaning we can loop (iterate) over its values. The range iterator calculates a new value on each call. This value is based on the start, stop, and step values.
If this sounds difficult: it is. If you don’t fully understand iterators and iterability, you have two options at this point:
- Read on and see how to use ranges. I won’t blame you.
- Read up on iterators and iterables first and then come back here.
If you’re looking to properly learn Python, I advise you to do yourself a favor and pick option two.
How to use Python range
There are three ways to use range. We’ll look at all three in detail, starting with the simplest use case. To give you a thorough understanding of the Python range function, I’ll show you exactly how a range works internally later on; it’s actually quite simple! However, it’s better to look at examples of how to use ranges first so you get a better idea of what they are and what they are capable of.
Range with only a stop value
If we call range with one argument, that argument is the stop value. In this case, range will start counting at 0 until it reaches the stop value.
For example, if we call range(5) , the created range object will return values 0, 1, 2, 3, and 4 when we iterate over it. So, important to note: range stops as soon as it reaches the stop value, and won’t return the stop value itself.
If that sounds confusing, a simple example will hopefully clarify it. Let’s use the range call in a for-loop:
Why does range not include the end value?
You might be wondering why range doesn’t include the end value. It all comes down to an important principle called zero-based indexing. Computers start counting at zero, while humans start counting at 1. When a computer needs to number 3 elements, it starts with element 0, then 1, and then 2. It’s the same with indexing. When accessing elements in a Python list, the first element resides at position 0. We would access it like this: my_list[0] .
Because of this zero-based indexing, it’s way easier if Python ranges start counting at zero too. E.g., if you want to loop through something using a range, you’ll probably want to start at element zero.
Range with start and stop value
We don’t always want to start counting at zero, and that’s why we can also call range with both a start and stop value. A call to range(2, 5) will return the values 2, 3, and 4. Here’s another example:
Range with a positive step size
Finally, range () takes an optional argument that’s called the step size. The step size defines how big each step is between the calculated numbers. It’s best to just illustrate this:
Each step skips a number since the step size is two. Let’s increase the step size:
Because we set stop to 101, the value 100 is included in this range as well.
Range with a negative step size
Ranges can count backward as well. If we set the step size to a negative number, the range will count backward. If we want to count backward, we need to make sure that the value for start is larger than the value for end . Here’s an example:
We started at 5 and counted backward to 0. Because ranges don’t include the end value itself, 0 was not included. If you want to include 0, you need to set end to -1.
How a Python range works
Now that you’ve seen range in action, I’ll tell you how ranges work internally to best understand them. There’s not much magic to it, actually!
A range is an iterable object, and this object can return an iterator that keeps track of its current state. Suppose we create a range with the call range(3) . This returns an object of type range with our requested settings. Internally, a Python range will set the following internal variables:
- the start value to 0,
- the end value to 3,
- and the step value to the default value of 1.
When we start iterating a range object, the range object will return an iterator. This iterator uses the values as defined above, but has one extra: a counter variable i , that is initialized to 0 by default and increases on each iteration.
On each call to the iterator to get the next number, range looks at its internal state and calculates the next number to return. The next value is calculated like this:
next = start + step*i .
By default, range takes steps of size one:
- So on the first call, the calculation that is made is this: 0 + 1*0 == 0 . Range returns 0 and the counter i is increased by 1, making i == 1
- On the 2nd call, it makes the same calculation with its current state: 0 + 1*1 = 1 . It again increases the counter i to 2.
- The 3rd call returns 2, since 0 + 1*2 == 2 .
- We’ve now reached the end of the range. As explained in my article on Python iterators, any following call to the iterator will return a StopIteration exception, signaling that there are no more items.
If you give your range a step size of 2 with range(0, 5, 2) , you can repeat the calculations from above and see that the returned values are now: 0 and 2.
Demonstrated with code
We can actually demonstrate this process with some code. In the example below, we first create a range object. Next, we manually request an iterator from the range object using the built-in iter() function. We start requesting the next value from it using another built-in function: next() . After 3 calls, you see that the iterable is exhausted and starts raising StopIteration exceptions:
If you like, you can run this code for yourself too:
Python range: Iterable or iterator?
A range object is an iterable, meaning that it is an object that can return an iterator. As you’ve seen in the example above, we can obtain this iterator manually with the iter() function. When used in a for-loop, the iterator is requested automatically by the loop and all is taken care of.
The range object (the iterable) will return a new iterator on each call. So, although this is not how we typically use ranges, we can actually keep using a range object by requesting new iterators from it. If you want to understand this in detail, read up on iterables and iterators.
Python range vs list
Ranges offer one big advantage over lists: they require a constant, predictable amount of memory since they are calculated on the fly. All a range needs to keep track of, are the start, stop, end, and iteration counter. So range(1000) requires the same amount of memory as range(1).
In contrast: a list with the values 0 to 999 takes a thousand times more memory than a list with just the value 1.
In Python 2 this wasn’t the case. The regular range would materialize into an actual list of numbers. At some point, xrange was introduced. In Python 3, it was decided that xrange would become the default for ranges, and the old materialized range was dropped. In addition, some extra features were added, like the ability to slice and compare ranges.
The name xrange does not exist in Python 3. If you encounter it, you’re likely looking at Python 2 code. I created an article on this subject if you want to convert it to Python 3 code.
Python Ranges in practice
What follows are some common and some less common operations on and with ranges that you might need in practice, besides using them for loops.
Convert range to list
We learned that ranges are calculated, while lists are materialized. Sometimes you want to create a list from a range. You could do this with a for-loop. Or, more Pythonic and quicker: by using a Python list comprehension. However, the best way to do this is using the list() function, which can convert any iterable object to a list, including ranges:
Testing for membership
Ranges behave like a regular collection, hence we can also test them for membership of a certain value. E.g., to test if a number is part of a range, you can do this:
Range slicing
Although I’m not sure you’ll ever need this (I never used it in practice), this is a pretty cool feature. Just like you can slice lists and other objects that have a sequence type, you can also slice a range object. When doing so, you might expect that the range is materialized to a list. That’s not the case. Instead, a new range object is calculated and returned, as you can see in the following examples on the Python REPL:
Comparing ranges
Finally, ranges can be compared as well. When comparing ranges, they are compared as sequences. You might expect that Python only checks if they are the same object. This used to be true until Python 3.3 came out. Since then, two different ranges that result in the same sequence will be seen as equal in Python.
Here are some examples on the REPL:
In the last example, a range with start 4 and end 2 will result in a range of length zero, hence it is equal to a range(0) .
Conclusion
You’ve learned about Python’s range and how to use it in a for-loop. Not only that; you’ve also learned how a range works internally. Besides these basics, you’ve learned how to convert a range to a list, that ranges can be compared, tested for membership and that we can even slice a range.
If you want to learn more about ranges, these resources might be of interest:
- My article on Python iterators and iterability on ranges by Trey Hunner, explaining in detail why range is not an iterator (but it is an iterable)
Get certified with our courses
Our premium courses offer a superior user experience with small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.



Learn more
This article is part of the free Python tutorial. You can head over to the start of the tutorial here. You can navigate this tutorial using the buttons at the top and bottom of the articles. To get an overview of all articles in the tutorial, please use the fold-out menu at the top.
If you liked this article, you might also like to read the following articles:
Функция range#
Функция range возвращает неизменяемую последовательность чисел в виде объекта range.
start — с какого числа начинается последовательность. По умолчанию — 0
stop — до какого числа продолжается последовательность чисел. Указанное число не включается в диапазон
step — с каким шагом растут числа. По умолчанию 1
Функция range хранит только информацию о значениях start, stop и step и вычисляет значения по мере необходимости. Это значит, что независимо от размера диапазона, который описывает функция range, она всегда будет занимать фиксированный объем памяти.
Самый простой вариант range — передать только значение stop:
Если передаются два аргумента, то первый используется как start, а второй — как stop:
И чтобы указать шаг последовательности надо передать три аргумента:
С помощью range можно генерировать и убывающие последовательности чисел:
Для получения убывающей последовательности надо использовать отрицательный шаг и соответственно указать start — большим числом, а stop — меньшим.
В убывающей последовательности шаг тоже может быть разным:
Функция поддерживает отрицательные значения start и stop:
Объект range поддерживает все операции, которые поддерживают последовательности в Python, кроме сложения и умножения.
Проверка, входит ли число в диапазон, который описывает range:
Начиная с версии Python 3.2, эта проверка выполняется за постоянное время (O(1)).
Что такое range в python
The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequence on a sequence of numbers using Python loops.
Syntax of Python range() function
Syntax: range(start, stop, step)
- start: [ optional ] start value of the sequence
- stop: next value after the end value of the sequence
- step: [ optional ] integer value, denoting the difference between any two numbers in the sequence.
Example of Python range() function
Python3
Output:
What is the use of the range function in Python
In simple terms, range() allows the user to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end, as well as how big the difference will be between one number and the next. Python range() function takes can be initialized in 3 ways.
- range (stop) takes one argument.
- range (start, stop) takes two arguments.
- range (start, stop, step) takes three arguments.
Python range (stop)
When the user call range() with one argument, the user will get a series of numbers that starts at 0 and includes every whole number up to, but not including, the number that the user has provided as the stop.

Python range visualization
Example: Demonstration of Python range (stop)
Python3
Output:
Python range (start, stop)
When the user call range() with two arguments, the user gets to decide not only where the series of numbers stops but also where it starts, so the user don’t have to start at 0 all the time. Users can use range() to generate a series of numbers from X to Y using range(X, Y).
Python range visualization
Example: Demonstration of Python range (start, stop)
Python3
Output:
Python range (start, stop, step)
When the user call range() with three arguments, the user can choose not only where the series of numbers will start and stop, but also how big the difference will be between one number and the next. If the user doesn’t provide a step, then range() will automatically behave as if the step is 1. In this example, we are printing even numbers between 0 and 10, so we choose our starting point from 0(start = 0) and stop the series at 10(stop = 10). For printing an even number the difference between one number and the next must be 2 (step = 2) after providing a step we get the following output (0, 2, 4, 8).