In this article, we will learn how to use Python’s `range()`

function with the help of different examples. Python built-in function `range()`

generates the **integer numbers between the given start integer to the stop integer**, i.e., It returns a range object. Using `for`

loop, we can iterate over a sequence of numbers produced by the `range()`

function.

Let’s understand how to use a `range()`

function of Python 3 with the help of a simple example.

print("Python range() example") print("Get numbers from range 0 to 6") for i in range(6): print(i, end=', ')

**Output**: Run Online

Python range() example Get numbers from range 0 to 6 0, 1, 2, 3, 4, 5,

**Note**: We got integers from 0 to 5 because `range()`

function doesn’t include the last (stop) number in the result.

**Free Bonus**

- Try to solve a Python range() and for loop Exercise
- Also, Explore All Python Exercises and Python Quizzes for
**Beginners**to Practice and master Python

Now understand the various usage of `range()`

function in detail.

Table of Contents

- Python range() function syntax and arguments
- Python range() with for loop
- Python range inclusive
- Python range Step
- Convert Python range() to List
- Using float Numbers in Python range()
- Reverse range in Python
- Concatenating the result of two range() function in Python
- Access Python range() output with its index value
- Python’s range() vs xrange() Functions
- Python range() over character or alphabet
- So What Do You Think?

## Python range() function syntax and arguments

**Syntax**:

range (start, stop[, step])

`range()`

takes three arguments. Out of the three 2 arguments are optional. I.e., start and step are the optional arguments.

- A
**start**argument is a starting number of the sequence. i.e., lower limit. By default, it starts with 0 if not specified. - A
**stop**argument is an upper limit. i.e., generate numbers up to this number, The`range()`

function doesn’t include this number in the result. - The
**step**is a difference between each number in the result. The default value of the step is 1 if not specified.

### Python range() function Examples

Let see all the possible scenarios now. Below are the **three variant of range()** function.

**Example one – Using only one argument in range()**

print("Print first 5 numbers using range function") for i in range(5): print(i, end=', ')

**Output**: Run Online

Print first 5 numbers using range function 0, 1, 2, 3, 4,

Only stop argument is passed to `range()`

function. So by default, it takes `start = 0`

and `step = 1`

.

**Example Two – using two arguments (i.e., start and stop) in range() function**

print("Print integers within given start and stop number using range() function") for i in range(5, 10): print(i, end=', ')

**Output**: Run Online

Print integers within given start and stop number using range() function 5, 6, 7, 8, 9,

Only two arguments (the start and stop) are passed to the `range()`

function. So by default, it took step value as 1.

**Example Three – using all three arguments in range() function**

print("using start, stop, and step arguments in Python range() function") print("Printing All odd numbers between 1 and 10 using range()") for i in range(1, 10, 2): print(i, end=', ')

**Output**: Run Online

using start, stop, and step arguments in Python range() function Printing All odd numbers between 1 and 10 using range() 1, 3, 5, 7, 9,

All three arguments are specified i.e., `start = 1`

, `stop = 10`

, `step = 2`

. The step value is 2 so the difference between each number is 2.

**⊗** Simple Practice Problem

Generate a range of numbers from 9 to 100 divisible by 3 in Python using `range()`

function.

**Read more**: Python for loop and range() Exercise

### Points to remember about Python range() function arguments

`range()`

function only works with the integers.**All arguments must be integers**. You can not pass a string or float number or any other type in a start, stop and step argument of a.`range()`

- All three
**arguments can be positive or negative**. - The step value must not be zero. If a step is zero Python raises a
**ValueError**exception.

## Python range() with for loop

As you know for loop executes a block of code or statement repeatedly for the fixed number of times. Using for loop we can iterate over a sequence of numbers produced by the `range()`

function.

Python `range()`

function uses the generator to produce numbers within a range, i.e., it doesn’t produce all numbers at once. The `range()`

function generates the next value within a range only when for loop iteration asked for it. In each loop iteration, we get the next value.

Let’ see how to use `range()`

with for loop to count the square of the first four numbers.

print("range() with for loop example to calculate square root") for i in range(1, 5): square = i**2 print("square of", i, "is", square)

**Output**: Run Online

range() with for loop example to calculate square root square of 1 is 1 square of 2 is 4 square of 3 is 9 square of 4 is 16

**Note**: The variable `i`

is not getting the value 0, 1, 2, 3, 4 at the same time. The value of `i`

changes sequentially. i.e., in the first iteration `i= 0`

. in the second iteration, `i`

become **1** and so on.

**⊗** Simple Practice Problem

Print the following number pattern using Python `range()`

and for loop.

1 2 2 3 3 3

**Read More**:

### How does Python’s range() function work?

Python `range()`

uses the generator to produce numbers within a range, i.e., it doesn’t produce all numbers at once. The `range()`

function generates the next value within a range only when for loop iteration asked for it.

In every iteration of for loop, `range()`

generates the next number and assigns it to the iterator variable of for loop. i.e., `range()`

function generates the numbers on demand. That means it produces number one by one as the loop moves to the next iteration. `range ()`

is faster and saves memory because it is not generating all numbers at once.

Also, **why does Python range(start, end) not include end**? It has a very simple answer because the index always starts with ZERO in Python. If you count total numbers between

`range (5)`

you will get `[0, 1, 2, 3, 4]`

i.e., the total count is 5.## Python range inclusive

The ** range(n) is of exclusive nature** that is why it doesn’t include the last number in the output. i.e., The given endpoint is never part of the generated result.

For example, `range(0, 5) = [0, 1, 2, 3, 4]`

. The result contains numbers from 0 to up to 5 but not 5. If you want to include the last number in the output i.e., If you want an inclusive range then pass `stop`

argument value as `stop+step`

.

**Inclusive range() example in Python**.

print("Printing inclusive range") start = 1 stop = 5 step = 1 stop +=step #now stop is 6 for i in range(start, stop, step): print(i, end=', ')

**Output**: Run Online

Printing inclusive range 1, 2, 3, 4, 5,

**Example 2: Inclusive range**

print("Printing inclusive range") start = 2 stop = 10 step = 2 stop +=step #now stop is 12 for i in range(start, stop, step): print(i, end=', ')

**Output**: Run Online

Printing inclusive range 2, 4, 6, 8, 10,

## Python range Step

A step is an optional argument of a `range()`

. The step is a **difference between each number** in the result sequence. If the step size is 2, then the difference between each number is 2. The default size of a step is **1** if not specified.

We can perform lots of operations by effectively using step arguments such as reversing a sequence, printing negative ranges.

### Decrementing with range() using a negative step

We can use negative values in all the arguments of `range()`

function i.e., start, stop and step.

start = -2 stop = -10 step = -2 print("Negative number range") for number in range(start, stop, step): print(number, end=', ')

**Output**: Run Online

Negative number range -2, -4, -6, -8,

Let’s understand the above program:

we set, `start = -2`

, `stop = -10`

, `step = -2`

.

- In the 1st iteration of for loop, the result is
`-2`

- In the 2nd iteration of for loop, the result is
`-2, -4`

because`-2+(-2) = -`

4 and so on. - And Last iteration output is
`-2, -4, -6,-8`

**Decrementing with the range from Negative to Positive number**

Here in this example, we can learn how to use a `step`

argument to display a range of numbers from negative to positive.

print ("printing range from negative to positive") for num in range(-2, 5, 1): print(num, end=", ")

The output of the above program

printing range from negative to positive -2, -1, 0, 1, 2, 3, 4,

**Python range from Positive to Negative number**

Here in this example, we can learn how to use step argument effectively to display numbers from positive to negative.

print (" printing range from Positive to Negative") for num in range(2,-5,-1): print(num, end=", ")

**Output**: Run Online

printing range from Positive to Negative 2, 1, 0, -1, -2, -3, -4,

## Convert Python range() to List

If you execute `print( type( range(10) ) )`

you will get `<class 'range'>`

as output. Python `range()`

function doesn’t return a list type. It returns a range object, i.e., sequence object of type range, So as a result, we get an immutable sequence object of integers.

We can convert the output of a `range()`

to the Python list. **Use list class to convert range output to list**. Let’s understand this with the following example.

print("Converting python range() to list") even_list = list( range(2, 10, 2)) print("printing list", even_list)

**Output**: Run Online

Converting python range() to list printing list [2, 4, 6, 8]

We can also use `range()`

function to access Python list items using its index number.

print("Use of range() to access Python list using index number") sample_list = [10, 20, 30, 40, 50] for i in range(len(sample_list)): print("List item at index ", i, "is ", sample_list[i])

**Output**: Run Online

Use of range() to access Python list using index number List item at index 0 is 10 List item at index 1 is 20 List item at index 2 is 30 List item at index 3 is 40 List item at index 4 is 50

**Note**: Using a `len(list)`

, we can get a count of list items, We used this count in `range()`

to iterate for loop fixed number of times.

## Using float Numbers in Python range()

**Python range() function doesn’t support the float numbers**. i.e., we cannot use floating-point or non-integer numbers in any of its arguments. we can use only integer numbers.

However, we can create a custom range function where we can use float numbers like 0.1 or 1.6 in any of its arguments. I have demonstrated this in the below example.

def frange(start, stop=None, step=None): if stop == None: stop = start + 0.0 start = 0.0 if step == None: step = 1.0 while True: if step > 0 and start >= stop: break elif step < 0 and start <= stop: break yield ("%g" % start) # return float number start = start + step print ("Printing float range") floatList = frange(0.5, 1.0, 0.1) for num in floatList: print (num)

**Output**: Run Online

Printing float range 0.5 0.6 0.7 0.8 0.9

Also, see All other ways to use float numbers in range() function.

## Reverse range in Python

If you want to print the sequence of numbers within range by descending order or reverse order then its possible, there are two ways to do this.

**The first is to use a negative or down step value**. i.e., set the `step`

argument of a `range()`

to `-1`

. For example, if you want to display a number sequence like [5, 4, 3, 2, 1, 0] i.e., we want reverse iteration or backward iteration of for loop with `range()`

function.

Let’s see how to **loop backward using indices** in Python to display a range of numbers from 5 to 0.

print ("Displaying a range of numbers by reverse order") for i in range(5, -1, -1): print (i, end=', ')

**Output**: Run Online

Displaying a range of numbers by reverse order 5, 4, 3, 2, 1, 0

**Use the reversed function to reverse range in Python**

Alternatively, using The `reversed()`

function, we can reverse any sequence. If we use the `reversed()`

function with `range()`

, that will return a ** range_iterator** that accesses the given range of numbers in the reverse order. The below example will let you know how to make a reverse for loop in Python.

print("Printing reverse range using reversed()") for i in reversed(range(0, 5)): print(i)

**Output**: Run Online

Printing reverse range using reversed() 4 3 2 1 0

Check the **output type** if we use `range()`

with `reversed()`

print("Checking the type") print(type(range(0, 5))) print(type(reversed(range(0,5))))

Output:

Checking the type <class 'range'> <class 'range_iterator'>

Also, If you need the list out of it, you need to convert the output of the `reversed()`

function to list. So you can get the reverse list of ranges.

**Print a list in reverse order with range().**

print("Printing list in reverse order with range") reverseed_list = list(reversed(range(0, 5))) print(reverseed_list) print("Second example to reverse list with range") reverse_list2 = list(range(5, -1, -1)) print(reverse_list2) print("Third Example to reverse list with range") reverse_list3 = list(range(2, 20, 2)[::-1]) print(reverse_list3)

**Output**: Run Online

Printing list in reverse order with range [4, 3, 2, 1, 0] Second example to reverse list with range [5, 4, 3, 2, 1, 0] Third Example to reverse list with range [18, 16, 14, 12, 10, 8, 6, 4, 2]

## Concatenating the result of two range() function in Python

Let say you want to add `range(5) + range(10,15)`

. (**Note**: this code is a pseudo-code.) And you want the concatenated range like `[0, 1, 2, 3, 4, 10, 11, 12, 13, 14]`

.

We can concatenate the output of two range functions using the **itertools’s ** function.

`chain()`

Program: Concatenating two range function results.

from itertools import chain print ("Concatinated two range() function") concatenated_range = chain(range(10), range(50, 75)) for num in concatenated_range: print(num,end=", ")

**Output**: Run Online

Concatinated two range() function 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,

## Access Python range() output with its index value

`range()`

is the constructor returns a range object which is nothing but a sequence of numbers, this range object can also be accessed by its index number using **slice notation**. It supports both positive and negative indices. The below example explains the same.

print("accessing Python range objet with its index") first_number = range(0,10)[0] #printing 0th position number i.e. index ZERO means first number print("First number in given range is: ", first_number) fifth_number = range(0,10)[4] print("fifth number in given range is: ", fifth_number)

**Output**: Run Online

accessing Python range objet with its index First number in given range is: 0 fifth number in given range is: 4

## Python’s range() vs xrange() Functions

The `range()`

and `xrange()`

comparison is relevant only if you are using both Python 2 and Python 3. If you are **not using Python 2 you can skip this comparison**.

## Python range() over character or alphabet

Is there a way to print a range of characters or alphabets? For example like this.

for char in range ('a','z'): print (char)

**Note**: The above code is a pseudo-code.

It is possible to print a range of characters using the custom generator. let’s see the example. in the following example, I have demonstrated how to **generate ‘a’ to ‘z’ alphabet using the custom range() function**. Here we used an ASCII value and then convert an ASCII value to a letter using a `Chr()`

function.

**Python Program to Generate letters from ‘a’ to ‘z’ using custom range() function**

print ("""Generates the characters from `a` to `z`, inclusive.""") def character_range(char1, char2): for char in range(ord(char1), ord(char2)+1): yield (char) for letter in character_range('a', 'z'): print( chr(letter), end=", " )

Generates the characters from `a` to `z`, inclusive. a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z,

## So What Do You Think?

I want to hear from you. What do you think of this guide on Python `range()`

?

Or maybe I missed one of the usages of Python’s `range()`

. Either way, let me know by **leaving a comment below**.

Also, try to solve the following Free Python Exercises and Quizzes to have a better understanding of Python’s `range()`

and `for`

loop.