One aspect of programming that many tutorials don’t tell you upfront is the amount of looping and counting you’ll have to do. As such, any programming language worth its salt will offer ways to enumerate numbers in a repeated way. The Python range sequence type is one of those methods.
In this post, we look at Python range()
and show you how it’s used within your programs.
Also read: Python While Loop: Intro and Explanation
Introducing the Python range() Sequence Type
Despite looking like a function, range()
is actually a built-in Python 3 immutable sequence type. As such, it’s grouped with lists and tuples as a way of collating data to loop later.
In short, it’s a way to repeat actions a certain number of times. In Python 2, it was called xrange()
and offered almost the same functionality. In fact, range()
is more powerful than xrange()
and has a few differences. We discuss the specifics further down.
As you’d expect, Python 3s range()
is great for looping tasks and iterating through lists and dictionaries. Let’s see how the function works.
How to Use the Python range() Sequence Type
First, let’s show you the basic structure of Python’s range()
:
range(y)
This is as simple as a Python function gets. Here, y
can be any integer (floating point numbers are not supported by default). Given the application, you’ll usually assign range()
to a variable. Once range() is run, it returns a tuple. If you print the assigned variable, you’ll see this tuple returned in the output.
In real-world applications, you’ll usually employ some form of looping, such as in this example using for
.
You’ll notice that range() uses zero as its starting point. However, this is only by default. In fact, range() has a number of other arguments you can set. Here’s the structure:
range(start, stop, step)
To explain: three integers are defined: a starting point, a stopping point, and whether the range skips numbers. Only the stop
argument is required – the others are optional.
This gives you much flexibility and power to construct both complex loops and tuples. For example, you could specify exact ranges of even integers.
What’s more, you can also combine functions to turn the generated tuple into a standard list.
Python range() isn’t only good for ascending iteration – it can be used for descending numbers, too.
In our opinion, range() is a real workhorse and will no doubt find much use in your programs.
In Conclusion
Python is great at many power applications, but generating lists, dictionaries, and tuples is a strong point. By using the Python range() sequence type, you can rapidly construct a tuple containing only the numbers you require. What’s more, Python lets you combine range() with other functions, such as list()
, to offer you flexibility in how you store those generated numbers.
If you’ve not yet made the jump to Python 3 and are using macOS, we’ve previously published an article that shows you how to do it.
Our latest tutorials delivered straight to your inbox