The Python range function is used to generate a sequence of numbers between a given range of values. In this guide, you’ll learn all you need to know about the Python
range() function by way of helpful examples. While on the surface, the function is very straightforward, there is a lot of hidden functionality.
By the end of this tutorial, you’ll have learned:
- How to use the Python
- How to customize the Python
range()with start, stop, and step parameters
- How to reverse the Python
- How to use the Python
range()function in a for loop
- And so much more
Understanding the Python range() Function
The Python range() function allows you generate a sequence of numbers using start, stop, and step parameters. By default, the created range will start from 0, increment by 1, and stop before the specified number.
Before we go any further, let’s make a quick note. Python
range() isn’t actually a function – it’s a type. When you instantiate a
range() object, a
range type is returned. The benefit of this is that it uses much less memory than container types, like lists or tuples. To keep things simple and practical, this guide will use the term function, rather than type.
Now, let’s take a look at how we can use Python range() by exploring its parameters and default arguments:
# Understanding the Python range() type range(start=0, stop, step=1)
We can see that the range() function has three parameters, only one of which is required. Let’s take a closer look at these parameters:
|Parameter||Description||Default Argument||Accepted Types|
|start=||The value to start the range at.||0||int|
|stop=||The value to stop the range at (not included).||N/A||int|
|step=||The value to increment by.||1||int|
By default, the range function will start at 0, increment by 1, and go up to (but not include) the value indicated at the stop parameter.
Creating a Python range() Object
Let’s see how we can use the
range() function to create a range of values:
# Creating a Range of Numbers with Python range() values = range(5) print('values contains: ', values) print('values is of type: ', type(values)) # Returns: # values contains: range(0, 5) # values is of type: <class 'range'>
In the code above, we passed in a range of values from 0 through, but not including, 5. There are two key takeaways from the code block above:
- Printing the
rangedoesn’t print out the values, but prints out the range object itself
- Instantiating a range returns a class of type
Python actually generates a lazy-loading object. To learn more about how these objects, or generators work, check out my complete guide on Python generators.
Printing Values in a Python range() Object
We can print out the values by iterating over each item in the object. We’ll print each of the item on the same line by modifying the
end= parameter of the
print() function. By passing in a string containing only a space, each item is printed on the same line, separated by a space.
# Printing Out Values in a range Object values = range(5) for value in values: print(value, end=' ') # Returns: # 0 1 2 3 4
We can see that the function returns values from 0 to 4. What’s more, is that the function returns an object containing five items.
Let’s take a look at how we can customize the start of our range in Python.
Customize the Start Value in the Python range() Function
By default, the Python range() will start 0. However, you can customize this value by modifying the
start= parameter. Let’s see how we can start our range at 5 and go up to 10 by passing in our parameters:
# Modifying the Start Value of the Python range() Function values = range(5, 10) for value in values: print(value, end=' ') # Returns: # 5 6 7 8 9
By passing in a
start= parameter, we can modify the starting position of the range. The start parameter is inclusive, meaning that the value is included (unlike the stop parameter). In the following section, you’ll learn about the final parameter,
Customize the Step in the Python range() Function
step= parameter of the Python range() function allows you to specify how values are incremented (or decremented) by. By default, this value is set to 1, meaning that items go from the start up to the stop, incrementing by 1.
Let’s see how we can pass in a different value to step through our range using different values:
# Customizing the Step of Python ranges values = range(0, 7, 2) for value in values: print(value, end=' ') # Returns: # 0 2 4 6
In the code above, we create a range from 0 through 7, incrementing by 2. This means that we’re creating a range of even numbers from 0 to 7.
Now that you have learned about all the different parameters available in the
range() type, let’s take a look at some use cases and quirks of the object.
Using Python range() In a For Loop
In many cases, you’ll use the Python
range() object in a to perform an action multiple times. We easily do this while accessing the item in our loop.
What’s great about this is that it lets you easily specify the number of times you want a piece of code to run. For example, passing in
range(5) identifies that a for loop will run five times.
Let’s see what this looks like:
# Looping While Accessing Items in the Range for val in range(5): print(val, 'Welcome to datagy.io') # Returns: # 0 Welcome to datagy.io # 1 Welcome to datagy.io # 2 Welcome to datagy.io # 3 Welcome to datagy.io # 4 Welcome to datagy.io
We can see that we were able to access the items in the range while executing code multiple times.
If you don’t need to access the item, you can identify this in your for loop by using an underscore. This makes it clear to the reader of your code that the item being iterated is a throw-away. Let’s see what this looks like:
# Looping Using range() Without Accessing Items for _ in range(5): print('Welcome to datagy.io') # Returns: # Welcome to datagy.io # Welcome to datagy.io # Welcome to datagy.io # Welcome to datagy.io # Welcome to datagy.io
In the following section, you’ll learn how to create a Python range in reverse.
Creating a Python Range in Reverse
Python makes it easy to generate a range in reverse by passing a negative value into the step parameter. When you pass a negative step value into the
range() object, you’re able to create a sequence of values in reverse order.
Let’s see how this works by creating a range that decrements by 1 from 5 to 0:
# Creating a Python Range in Reverse for val in range(5, 0, -1): print(val, end=' ') # Returns: 5 4 3 2 1
Similarly, you can create ranges of negative values using this negative step as well. Let’s create a new range going from 0 through to -10:
# Creating a Range of Negative Values by Decrementing for val in range(0, -10, -1): print(val, end=' ') # Returns: 0 -1 -2 -3 -4 -5 -6 -7 -8 -9
In the following section, you’ll learn how to create a list from a Python range.
How to Create a List from a Python Range
When you first create a
range object, the values are stored in a memory-efficient format. However, in some cases, you’ll want to convert the ranges you create into Python lists.
Thankfully, this is made easy by using the
list() constructor function. You can simply pass the range into the
list() function, which creates a list out of the range.
Let’s see what this looks like:
# Converting a Python Range Into a List list_of_values = list(range(5)) print(list_of_values) # Returns: [0, 1, 2, 3, 4]
Keep in mind that by creating a list out of the range object, you’re losing the memory efficiency that the range object has.
How to Use Python range with Floats
By default, the
range() function only works with integers. In fact, by passing in floats your program will raise a
TypeError. This is an important consideration and may cause some confusion.
# Raising a TypeError When Creating a Range of Floats values = range(2.0) # Raises: TypeError: 'float' object cannot be interpreted as an integer
In fact, there is no direct way of creating a range object with a float. However, we can create a list out of our range object and convert each item to its floating point representation.
# Creating a List of Floats Using a For Loop values = range(5) floats =  for value in values: floats.append(float(value)) print(floats) # Returns: [0.0, 1.0, 2.0, 3.0, 4.0]
In the code block above, we used a for loop to iterate over each element in the range. We then converted the item to a floating point value using the
float() function and appended it to a list.
We can also simplify this process by making use of a Python list comprehension to simplify our code. Let’s take a look at how we can do this:
# Creating a List of Floats Using a List Comprehension values = range(5) floats = [float(val) for val in values] print(floats) # Returns: [0.0, 1.0, 2.0, 3.0, 4.0]
In some cases, you’ll want to create a range of floating point values that increment at a decimal values. For this, you can use NumPy’s
Creating Ranges with Floats using NumPy
arange() function allows you to create ranges with floating point values. By doing this, you can create ranges that do not increment by whole numbers. Let’s see how we can create a range of floating point values from 1.0 through 10.0 that increment by 1.5:
# Using NumPy to Create Ranges of Floating Point Values import numpy as np floats = np.arange(1.0, 10.0, 1.5) print(floats) # Returns: [1. 2.5 4. 5.5 7. 8.5]
Let’s break down what we did in the code block above:
- We imported NumPy using the alias
- We then used the
arange()function to create a range of values going from 1.0 through 10.0 incrementing by 1.5
In the following section, you’ll learn how to use the Python range() function to create an inclusive range.
How to Use Python Range Inclusively
There is no default way to create an inclusive range in Python. However, you can make the range inclusive by simply adding the step value to the stop value. This ensures that the stop value will be included in the range.
Let’s see what this looks like:
# Creating an Inclusive Range in Python step = 1 values = range(0, 5 + step, step) for value in values: print(value, end=' ') # Returns: 0 1 2 3 4 5
In the following section, you’ll learn how to create a negative range in Python.
How to Create a Negative Range in Python
In general, Python will not produce anything when you pass only a negative value into the
range() function. Let’s see what this looks like:
# Passing Only a Negative Value to the range() Function values = range(-10) for value in values: print(value, end=' ') # Returns:
Logically, this makes sense! Because the start value defaults to 0 and the step argument defaults to 1, Python can’t go from 0 to a negative value!
In order to create negative ranges, we have two options:
- We can create a negative range in increasing order, or
- We can create a negative range in decreasing order
If we want our range to increase in values, our start value must be smaller than our stop value. Similarly, our step must be positive. Let’s see what this looks like:
# Creating a Negative Range in Increasing Order values = range(-5, 0) for value in values: print(value, end=' ') # Returns: -5 -4 -3 -2 -1
In order to create a negative range with decreasing values, the following conditions must be true:
- The start must be higher than the stop
- The step must be negative
Let’s see what this looks like in Python:
# Creating a Negative Range in Decreasing Order values = range(-1, -6, -1) for value in values: print(value, end=' ') # Returns: -1 -2 -3 -4 -5
In the following section, you’ll learn how to index a Python range object.
Indexing a Python Range Object
One of the great things about Python
range objects is that they are indexable and sliceable. This allows you to access a specific element or slices of elements directly from the range.
This can be done by using
 square-bracket indexing on the range object. Let’s see how we can access the second item in a range by accessing the 1st index:
# Indexing Python Range Objects values = range(10) print(values) # Returns: 1
Similarly, we can use negative indexing to access items from the end of the range. Let’s see how we can access the second last item by indexing the index of -2:
# Using Negative Indexing in Python Range Objects values = range(10) print(values[-2]) # Returns: 8
We can even select slices of our range object by passing in a slice of values. Let’s see how we can access the first five items of a given range:
# Slicing a Python Range Object values = range(10) print(values[:5]) # Returns: range(0, 5)
Notice here, that the slice returns a range object in itself. In order to get the actual values, you can convert the object to a list using the
list() function. In the next section, you’ll learn how to access different attributes of a range object.
Accessing Start, Stop, and Step Attributes in a Python range Object
range objects are, well, objects, they come with different attributes. In particular, the range object has three attributes:
.start, which identifies the start of the range
.stop, which identifies the stopping point of the range
.step, which identifies the step of the range
Let’s create a Python range and print out these attributes:
# Printing Out Range Attributes in Python values = range(10) print('The start is: ', values.start) print('The stop is: ', values.stop) print('The step is: ', values.step) # Returns: # The start is: 0 # The stop is: 10 # The step is: 1
The following section will explore some frequently asked questions about the Python range function.
Frequently Asked Questions
The function returns a range object by passing in start, stop, and step arguments. If only a stop argument is provided, the range will increment by 1, starting at 0 up to (but not including) the stop value.
You can decrease a range in Python by passing in a negative step value. For example, range(10, 0, -1) will return the values from 10 through 1.
range is the Python 3 equivalent of xrange in Python 2. In Python 2, range returned a list, rather than a lazy-evaluating generator.
In this guide, you learned how to use
range() in Python to create sequences of values. You first learned how to use the range function by understanding its various parameters. Then, you learned how to customize the behavior of the function. The ranges you can create can be used with significant flexibility. Understanding all that this type has to offer can make you a much stronger Python programmer.
To learn more about related topics, check out the guides below: