7+ simple examples to learn python range() function


Written By - admin
Advertisement

Python's range function is a built-in function that generates a list of numbers. This list is mostly used to iterate over using a for loop.

 

Python range() vs xrange() function

In Python 2, for creating iterable objects, the xrange() function was used. In Python 3, range() is implemented much like xrange(). So, a separate xrange() is not needed anymore. Using xrange() in Python 3 raises a NameError.

 ~]# python3 --version
Python 3.6.8

I will try to use xrange() with python 3:

#!/usr/bin/env python3

print(range(10))
print(xrange(10))

Output from this script:

~]# python3 python-range-1.py
range(0, 10)
Traceback (most recent call last):
  File "python-range-1.py", line 4, in 
    print(xrange(10))
NameError: name 'xrange' is not defined

As expected we are getting NameError for xrange function.

 

Python range() function syntax

The basic syntax of the range function is as follows:

range([start], stop, [step])

Here is a breakdown of what each parameter does:

  • start: This is the starting number of the sequence.
  • stop: This means generate numbers up to but not including this number.
  • step: This is the difference between each number in the sequence.

The only required parameter when calling the range function is the stop parameter, and the default call to the function can have just that one parameter.

Advertisement
NOTE:

The values provided to the range function must be integers. Floating numbers and any other types are not allowed.

 

Python range(stop)

Now, let's look at some calls to the range function and their corresponding output. First off, perform a call with just the stop parameter included:

range(5)

The range(5) class basically tells the function to generate numbers from 0 to 5, but not including 5

Let's check the syntax of range(5):

#!/usr/bin/env python3

print(range(5))

Output from this script:

 ~]# python3 range-example-2.py
range(0, 5)

Since we didn't gave any start value, by default range() will consider 0 as the start value. So our syntax is updated internally to range(0,5)

To get the content of range(5) we can either change the data type to list or use a for loop to iterate over the values of range()

 

Example-1: Print range value using list

We will update our script to print the range(5) as list type:

Advertisement
#!/usr/bin/env python3

print(list(range(5)))

Output from this script:

 ~]# python3 range-example-2.py
[0, 1, 2, 3, 4]

 

Example-2: Use for loop to access range() function

Since range() is iterable, we can also use for loop to iterate over individual values of the range() function:

#!/usr/bin/env python3

for val in range(5):
    print(val)

Output from this script:

 ~]# python3 range-example-2.py
0
1
2
3
4

 

Python range(start, stop)

In the previous example since we didn't gave any start value, 0 was considered as the start. Now I use share some examples where we define our own start and stop value for range().

Example-1: Use for loop to iterate through range()

In this example we will use for loop to iterate over the numbers from range(10, 15)

#!/usr/bin/env python3

for val in range(10, 15):
    print(val)

Output from this script:

Advertisement
 ~]# python3 range-example-3.py
10
11
12
13
14

So as you see, this time the number count started from 10 instead of 0 since we had specified the start point.

 

Example-2: Using range() to Make a List of Numbers

As we did earlier, if you want to make a list of numbers, you can convert the results of range() directly into a list using the list() function. When you wrap list() around a call to the range() function, the output will be a list of numbers.

#!/usr/bin/env python3

print(list(range(10, 15)))

Output from this script:

 ~]# python3 range-example-3.py
[10, 11, 12, 13, 14]

 

Python range(start, stop, step)

We can also use the range() function to tell Python to skip numbers in a given range. If you pass a third argument to range(), Python uses that value as a step size when generating numbers.

Example-1: Generate even numbers as a List

In this example we will use step to get only the even numbers out of the provided range.

#!/usr/bin/env python3

even_numbers = list(range(2, 11, 2))
print(even_numbers)

Output from this script

~]# python3 range-example-3.py
[2, 4, 6, 8, 10]

Since we know any integer divisible by 2 is an even number so we have added a step value of 2 which will only give us the list on even numbers from the provided range.

 

Example-2: Generate odd numbers using for loop with range()

In this example we will use for loop to iterate over a range and print only odd numbers

#!/usr/bin/env python3

for num in range(1, 11, 2):
    print(num, end=' ')

Output from this script:

1 3 5 7 9

Here I have used end=' ' to print the output in the same line and remove the new line character from the end. Now since my range is starting from 1 to 11 I have kept step value as 2. But you may have to add additional if condition for a different range such as 2-10

 

Advertisement

Python range reverse with negative step value

The step value can be positive or negative depending on your requirement. Now in the earlier examples we were stepping up the range iterations with a positive value, in this example we will step down the range with negative value:

#!/usr/bin/env python3

for num in range(31, 11, -2):
    print(num, end=' ')
print()

Output from this script:

 ~]# python3 range-example-4.py
31 29 27 25 23 21 19 17 15 13

So this time our range was starting from 31 till 11 which is in descending order so we have given a negative step value hence the output contains integers in descending order.

 

Conclusion

In this tutorial we have looked into the Python range() function and how it comes in handy when you need to quickly iterate over a list. You can easily add additional conditions using start, stop and step within a range to get desired output. You can also use it to iterate over a list (or another iterable) while keeping track of the index.

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment