How to use Python Range – with example

  • Reading time:15 mins read

What is the Python Range function?

Python range() is an inbuilt function that generates a sequence of numbers. When we call the range function in Python, it creates an object of a range of numbers and it takes the arguments of start, stop and the step i.e range(start, stop, step).

 

How to create Python Range?

We can create a list of numbers using the range function, however, it is important to note that the stop number will not be included in the list.

 

 

If we change the start number to two then we will obtain a list of even numbers as shown in the code below.

 

Using a for loop to create a range of numbers

This is particularly useful when we want to add things together or maybe we want to add a number to a string for various reasons. The best way that we can do that is by using a for loop.

 

Python

 

So we’re going to do for x in range(). Now what this is going to do, is every loop through x is going to become the next number in our range because we’re using a list. Let’s do a range of 1,10. This is going to go look through each of the numbers, one through nine just as in the example above.

 

 

We can also add numbers using a loop and the Python range function. We can simply do that by changing the print statement to read print(x+5).

 

 

We can also create a descending list by simply changing the step within the range function to be a negative number. For instance, if we change the step to -1 it is going to count from ten up to but not including 1.

 

 

 

So if we wanted to go all the way down we needed to change the stop number to Zero.

 

 

We can also append this number to a text which can be quite useful depending on what you’re doing. To do that we need to print the word item and then use an additional sign to concatenate it with the integer being printed out by first converting it to a string, as illustrated in the code below. When we execute this code we’ll end up with a list of items with a number on the end.

 

 

Summary

This is how Python Range works in practice. If you’d like to see more programming tutorials, check out our Youtube channel, where we have plenty of Python video tutorials in English.

In our Python Programming Tutorials series, you’ll find useful materials which will help you improve your programming skills and speed up the learning process.

Programming tutorials

Would you like to learn how to code, online? Come and try our first 25 lessons for free at the CodeBerry Programming School.

Learn to code and change your career!

100% ONLINE

IDEAL FOR BEGINNERS

SUPPORTIVE COMMUNITY

SELF-PACED LEARNING

Not sure if programming is for you? With CodeBerry you’ll like it.