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

function with the help of different examples. The 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.

```
#Python range() example
print("Numbers from range 0 to 6")
for i in range(6):
print(i, end=', ')
```

**Output**:

Numbers from range 0 to 6 0, 1, 2, 3, 4, 5,

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

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

**Further reading**

- 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

**This Python range() tutorial cover the following topics:**

Table of Contents

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

## range() function syntax and arguments

**Syntax**

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

It 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()`

doesn’t include this number in the result. so the last number is`stop - step`

. - The
**step**is a difference between each number in the result. The default value of the step is 1 if not specified.

### range() function Examples

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

**Example one: **– Using only one argument

in this example, we will use only the stop argument of a `range()`

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

and `step = 1`

.

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

**Output**:

0, 1, 2, 3, 4,

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

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

**Output**:

5, 6, 7, 8, 9,

**Note**: By default, it took step value as 1.

**Example Three**: – using all three arguments

Here we will use all three arguments i.e., `start = 2`

, `stop = 10`

, `step = 2`

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

```
# using start, stop, and step arguments in range()
print("Printing all even numbers between 2 and 10 using range()")
for i in range(2, 10, 2):
print(i, end=', ')
```

**Output**:

Printing all even numbers between and 10 using range() 2, 4, 6, 8,

Practice Problem

Use `range()`

to generate a list of numbers from 9 to 100 divisible by 3.

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

`range()`

only works with the integers.**All arguments must be integers**. You can not use 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.

## for loop with range()

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

function. Let’s see how to use for loop and `range()`

function to **print the odd numbers between 1 and 10**. Using this example, we can understand how `i`

is getting its value when we use `range()`

and for loop together.

```
for i in range(1, 10, 2):
print("Current value of i is:", i)
```

**Output**:

Current value of i is: 1 Current value of i is: 3 Current value of i is: 5 Current value of i is: 7 Current value of i is: 9

**In for i in range() i is the iterator variable**. To understand what does

`for i in range()`

mean in Python, first, we need to understand the working of `range()`

function. The `range()`

function uses the generator to produce numbers within a range, i.e., it doesn’t produce all numbers at once. It generates the next value only when for loop iteration asked for it. In each loop iteration, Python generates the next value and assign it to the iterator variable `i`

.**Program execution**

- As you can see in the output, the variable
`i`

is not getting the value 1, 3, 5, 7, 9 at the same time. - In the first iteration of for loop value of
`i`

is the value of`start`

. i.e., The first value of`i`

is the starting number of a range. Here the range starts at 1. - Next, In every subsequent iteration of for loop, the value of
`i`

incremented sequentially. The value of`i`

is determined by the formula`i = i + step`

. i.e., in the second iteration,`i`

become 3, and so on.

As you know, In every iteration of for loop, `range()`

generates the next number and assigns it to the iterator variable `i`

. i.e., We get numbers on demand ( `range()`

produces number one by one as the loop moves to the next iteration). Because of this behavior `range()`

is faster and saves memory.

Practice Problem

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

and for loop.

1 2 2 3 3 3

**Read More**:

## Inclusive range

In this section, we will learn how to generate an inclusive range. 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 and the total count is 5. The `range(start, stop)`

not include stop number in the output because the index (i) always starts with 0 in Python.If you want to include the last number in the output i.e., If you want an inclusive range then set the `stop`

argument value as `stop+step`

.

**Inclusive range() example**

```
# 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**:

1, 2, 3, 4, 5,

**Example 2**

```
# 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**:

2, 4, 6, 8, 10,

## Python range step

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

. The `step`

is an integer value that determines the increment between each number in the sequence. so it is also the **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 value**

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**:

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() using positive step value**

Here in this example, we will learn how to use a step argument to **display a range of numbers from negative to positive**. Range of negative numbers.

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

The output of the above program

-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**:

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

## Reverse range

If you want to print the sequence of numbers within range by descending order or reverse order in Python then it’s 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**:

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**:

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 using 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**:

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]

## Convert 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**:

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**:

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 range()

**Python’s 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**:

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.

## Concatenating the result of two range() function

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**:

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 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**:

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

## 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**.

## 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.