Python `range()`

function generates the **immutable sequence of numbers** starting from the given start integer to the stop integer. The `range()`

is a built-in function that returns a range object that consists series of integer numbers, which we can iterate using a `for`

loop.

In Python, Using a for loop with `range()`

, we can repeat an action a specific number of times. For example, let’s see how to use the `range()`

function of **Python 3** to produce the first six numbers.

**Example**

```
# Generate numbers between 0 to 6
for i in range(6):
print(i)
```

**Output**

0 1 2 3 4 5

**Note**: As you can see in the output, We got six integers starting from 0 to 5. If you notice, `range()`

didn’t include 6 in its result because it generates numbers up to the stop number but **never includes the stop number in its result**.

The `range()`

works differently between Python 3 and Python 2.

- In Python 2, we have
`range()`

and`xrange()`

functions to produce a sequence of numbers. - In Python 3
`xrange()`

is renamed to`range()`

and original`range()`

function was removed. We will discuss it in the later section of the article.

## Table of contents

- How to use range() function in Python
- range() Examples
- for loop with range()
- Reverse range
- Python range step
- Negative range() in Python
- Convert range() to list
- Inclusive range
- range() vs. xrange() in Python 2
- Concatenating the result of two range()
- range() indexing and slicing
- range() over character or alphabet
- Summary
- FAQ

## How to use range() function in Python

### Syntax

Below is the syntax of the range() function.

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

It takes three arguments. Out of the three, two are optional. The `start`

and `step`

are optional arguments and the `stop`

is the mandatory argument.

### Parameters

`start`

: (Lower limit) It is the starting position of the sequence. The**default value is 0**if not specified. For example,`range(0, 10)`

. Here,`start=0`

and`stop = 10`

`stop`

: (Upper limit) generate numbers up to this number, i.e., An integer number specifying at which position to stop (upper limit). The`range()`

**never includes the stop number in its result**`step`

: Specify the increment value. Each next number in the sequence is generated by adding the step value to a preceding number. The**default value is 1**if not specified. It is nothing but a difference between each number in the result. For example,`range(0, 6, 1)`

. Here,`step = 1`

.

### Return Value

It returns the object of class `range`

.

```
print(type(range(10)))
# Output <class 'range'>
```

### Steps to use range() function

The `range()`

function generates a sequence of integer numbers as per the argument passed. The below steps show how to use the range() function in Python.

**Pass start and stop values to range()**For example,

`range(0, 6)`

. Here,`start=0`

and`stop = 6`

. It will generate integers starting from the`start`

number to`stop -1`

. i.e.,`[0, 1, 2, 3, 4, 5]`

**Pass the step value to range()**The

`step`

Specify the increment. For example,`range(0, 6, 2)`

. Here,`step = 2`

. Result is`[0, 2, 4]`

**Use for loop to access each number**Use for loop to iterate and access a sequence of numbers returned by a

`range()`

.

## range() Examples

Now, let’s see all the possible scenarios. Below are the three variants of `range()`

.

`range(stop)`

When you pass only one argument to the `range()`

, it will generate a sequence of integers starting from 0 to `stop -1`

.

```
# Print first 10 numbers
# stop = 10
for i in range(10):
print(i, end=' ')
# Output 0 1 2 3 4 5 6 7 8 9
```

**Note**:

- Here,
`start = 0`

and`step = 1`

as a default value. - If you set the
`stop`

as a 0 or some negative value, then the range will return an empty sequence. - If you want to start the range at 1 use
`range(1, 10)`

.

`range(start, stop)`

When you pass two arguments to the `range()`

, it will generate integers starting from the `start`

number to `stop -1`

.

```
# Numbers from 10 to 15
# start = 10
# stop = 16
for i in range(10, 16):
print(i, end=' ')
# Output 10 11 12 13 14 15
```

**Note**

- Here, the
`step = 1`

as a default value. - The range will return an empty sequence if you set the
`stop`

value lesser than the`start`

.

`range(start, stop, step)`

When you pass all three arguments to the range(), it will return a sequence of numbers, starting from the start number, increments by step number, and stops before a stop number.

Here you can specify a different increment by adding a `step`

parameter.

```
# Numbers from 10 to 15
# start = 10
# stop = 50
# step = 5
for i in range(10, 50, 5):
print(i, end=' ')
# Output 10 15 20 25 30 35 40 45
```

**Note**:

- Here, the
`step = 0`

as a default value. - Python will raise a
`ValueError`

exception if you set the`step`

to 0.

### Points to remember about range() function

- The
`range()`

function only works with the integers, So all arguments must be integers. You can not use float numbers or any other data type as a start, stop, and step value. Please refer to generate a range of float numbers in Python - All three arguments can be positive or negative.
- The
`step`

value must not be zero. If a`step=0`

, Python will raise a`ValueError`

exception.

**Practice Problem**: –

Use `range()`

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

## Show Solution

```
# start = 9
# stop = 100
# step = 3 (increment)
for i in range(9, 100, 3):
print(i)
```

## for loop with range()

Python for loop executes a block of code or statement repeatedly for a fixed number of times. We can iterate over a sequence of numbers produced by the range() function using for loop.

Let’s see how to use `for`

loop with `range()`

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

is getting value when we use range() with for loop.

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

**Output**

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

To understand what `for i in range()`

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

function.

The `range()`

function uses the generator to produce numbers. It doesn’t generate all numbers at once.

As you know range() returns the `range`

object. A range object uses the same (small) amount of memory, no matter the size of the range it represents. It only stores the start, stop and step values and calculates individual items and subranges as needed.

I.e., It generates the next value only when for loop iteration asked for it. In each loop iteration, It generates the next value and assigns it to the iterator variable i.

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

is not getting the values 1, 3, 5, 7, and 9 simultaneously. - In the first iteration of the loop value of
`i`

is the start number of a range. - Next, In every subsequent iteration of for loop, the value of
`i`

is incremented by the step value. The value of`i`

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

.

So it means range() produces numbers one by one as the loop moves to the next iteration. It saves lots of memory, which makes range() faster and more efficient.

### Iterate a list using `range()`

and `for`

loop

You can iterate Python sequence types such as list and string using a `range()`

and for loop.

When you iterate the list only using a loop, you can access only items. When you iterate the list only using a loop, you can only access its items, but when you use range() along with the loop, you can access the index number of each item.

The advantage of using `range()`

to iterate a list is that it allows us to access each item’s index number. Using index numbers, we can access as well as modify list items if required.

**Example**

Pass the count of total list items to `range()`

using a `len()`

function. The `range()`

will use it as a `stop`

argument.

```
list1 = ['Jessa', 'Emma', 20, 30, 75.5]
# iterate a list using range()
for i in range(len(list1)):
print(list1[i])
```

**Output**:

Jessa Emma 20 30 75.5

### Practice Problem

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

and a loop.

1 2 2 3 3 3

## Show Solution

```
for num in range(4):
for i in range(num):
print(num, end=" ")
print() # new line after each row to show pattern correctly
```

**Read More**:

## Reverse range

You can display the sequence of numbers produced by a `range()`

function by descending order or reverse order.

You can use the following two ways to get the reverse range of numbers in Python.

- Use a negative
`step`

value - Use a
`reversed()`

function

### Using negative step

Use a negative step value in a `range()`

function to generate the sequence of numbers in reverse order. For example, `range(5, -,1, -1)`

will produce numbers like 5, 4, 3, 2, and 1.

I.e., you can reverse a loop by setting the step argument of a `range()`

to -1. It will cause the `for`

loop to iterate in reverse order.

Let’s see how to loop in a reverse iteration or backward iteration to display a range of numbers from 5 to 0.

```
# reverse range using negative step
# start = 5
# stop = -1
# step = -1
for i in range(5, -1, -1):
print(i)
```

**Output**:

5 4 3 2 1 0

### Using reversed() function

Using Python’s built-in `reversed()`

function, you can reverse any sequence such as list or range.

- Pass the
`range()`

as an input to the reversed() function, It returns a`range_iterator`

that accesses the sequence of numbers provided by`range()`

in the reverse order. - Next, iterate the result provided by
`reversed()`

function using for loop.

**Example 2**: reverse range starting from 20 to 10

```
for i in reversed(range(10, 21)):
print(i, end=' ')
# Output 19 18 17 16 15 14 13 12 11 10
```

**Example 3**: reverse range starting from 20 to 10 with step 2

```
for i in reversed(range(10, 21, 2)):
print(i, end=' ')
# Output 20 18 16 14 12 10
```

**Note**: The `reversed(range(n))`

returns a `range_iterator`

that accesses the sequence of numbers provided by `range()`

in the reverse order.

```
print(type(range(0, 5)))
# Output <class 'range'>
print(type(reversed(range(0, 5))))
# Output <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.

### Use range() to reverse a list

Use `range()`

to reverse a list by passing the count of list items as a `start`

argument and `step`

as a -1.

Let’s see the various ways to reverse a list of numbers using a `range()`

```
list1 = [10, 20, 30, 40, 50]
# start = list's size
# stop = -1
# step = -1
# reverse a list
for i in range(len(list1) - 1, -1, -1):
print(list1[i], end=" ")
# Output 50 40 30 20 10
```

## Python range step

A step is an optional argument of a range(). It is an integer number that determines the increment between each number in the sequence. i.e., It specifies the incrementation.

You can also define it as a difference between each preceding and next number in the result sequence. For example, If the step is 2, then the difference between each preceding and following number is 2

The default value of the step is 1 if not specified explicitly.

**Example: Increment using step**

```
# range() step with default value
for i in range(10):
print(i, end=' ')
# Output 0 1 2 3 4 5 6 7 8 9
# Increment in range() with step = 2
# print table of 2 using range()
for i in range(2, 22, 2):
print(i, end=' ')
# Output 2 4 6 8 10 12 14 16 18 20
```

You can also perform lots of operations by using step arguments such as reverse a sequence such as a list and string.

### Decrementing range() using step

You can **decrement** range() by using negative `step`

value.

When we set the negative value to step, In each iteration, the number will go down until it reaches to stop number.

```
# Decrement range() using step
# start = 30, stop = 20
# step = -2
for i in range(30, 20, -2):
print(i, end=' ')
# Output 30 28 26 24 22
```

**Note**: To decrement `range()`

the `start`

must be greater than `stop`

. A range() return empty sequence if `start < stop`

.

```
for i in range(20, 30, -2):
print(i, end=' ')
```

Also, you can use `step`

to generate sequence of numbers multiply of n.

```
# Generate integers multiply by 7
for i in range(7, 77, 7):
print(i, end=' ')
# Output 7 14 21 28 35 42 49 56 63 70
```

Also, you will get a `valueerror`

if you set `step = 0`

.

```
for i in range(1, 5, 0):
print(i, end=' ')
# Output ValueError: range() arg 3 must not be zero
```

Also, you can’t use the decimal `step`

value. If you want to use the float/decimal step in the `range()`

, please refer to generating a range of float numbers.

## Negative range() in Python

You can use negative integers in range().

Most of the time, we use the negative step value to reverse a range. But apart from the step, we can use negative values in the other two arguments (start and stop) of a range() function.

**Example: Negative range from -1 to -10**

Let’s see the example to print the range of numbers from negative to positive.

```
# negative range from -1 to -10
for i in range(-1, -11, -1):
print(i, end=', ')
# Output -1, -2, -3, -4, -5, -6, -7, -8, -9, -10
```

Let’s understand the above program, we set –

`start = -1`

(because we wanted to start producing number from -1)`stop = -11`

(We want to stop generating numbers when we reach -11)`step = -1`

**Execution**:

- In the 1st iteration of the loop,
`i`

is -1 - In the 2nd iteration of for loop,
`i`

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

, and it will repeat this process till the stop number.

**Example: Negative reverse range from -10 to -1**

You can also print the negative reverse `range()`

using a positive `step`

integer.

```
# negative range from -10 to -1
# start = -10
# stop = 0
# step = 1
for i in range(-10, 0):
print(i, end=', ')
# Output -10, -9, -8, -7, -6, -5, -4, -3, -2, -1,
```

**Combination of negative and positive numbers**

```
# stat = 2, stop = -5, step = -1
for i in range(2, -5, -1):
print(i, end=", ")
# Output 2, 1, 0, -1, -2, -3, -4,
```

## Convert range() to list

Python `range()`

function doesn’t return a `list`

type. It returns an immutable sequence of integers.

We can convert `range()`

to list using a `list()`

constructor.

- Pass the
`range()`

function as an input to the list constructor. - The
`list()`

constructor automatically creates a list by enclosing the integers returned by the`range()`

inside the square brackets.

```
# create list from range()
sample_list = list(range(2, 10, 2))
print(type(sample_list))
# Output <class 'list'>
# display list
print(sample_list)
# Output [2, 4, 6, 8]
# iterate list
for item in sample_list:
print(item)
```

**Access and modify list item using range()**

Also, you can use `range()`

to access and modify `list`

items.

- Using a
`len()`

function, you can get a count of list items. - Next, use this count as a stop number in
`range()`

and iterate for loop`stop-1`

times. - In each iteration, you will get the index number of a current list item.

```
# create list from range()
sample_list = list(range(10, 100, 10))
# iterate and modify list item using range()
# double each list number
# start = 0, stop = list size, step =1
for i in range(0, len(sample_list), 1):
sample_list[i] = sample_list[i] * 2
# display updated list
print(sample_list)
# Output [20, 40, 60, 80, 100, 120, 140, 160, 180]
```

## Inclusive range

In this section, we will learn how to generate an inclusive range in Python. By default, The `range(n)`

is exclusive, so it doesn’t include the last number in the result. It creates the sequence of numbers from `start`

to `stop -1`

.

For example, `range(5)`

will produce `[0, 1, 2, 3, 4]`

. The result contains numbers from 0 to up to 5 but not five.

If you notice, the result contains **5 elements** which equal to `len(range(0, 5))`

. Note, the index always starts from 0, not 1.

If you want to include the end number in the result, i.e., If you want to create an inclusive range, then **set the stop argument value as stop+step**.

**Example**

```
# inclusive range
start = 1
stop = 5
step = 1
# change stop
stop += step
for i in range(start, stop, step):
print(i, end=' ')
# Output 1 2 3 4 5
```

**Example 2: Even inclusive range()**

```
step = 2
for i in range(2, 20 + step, step):
print(i, end=' ')
# Output 2 4 6 8 10 12 14 16 18 20
```

`range()`

vs. `xrange()`

in Python 2

The `range()`

vs `xrange()`

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

The range() function works differently between Python 3 and Python 2. If your application runs on both Python 2 and Python 3, you must use `range()`

instead of `xrange()`

for better code compatibility.

In Python 2, we have `range()`

and `xrange()`

functions to produce a sequence of numbers.

In Python 3 `xrange()`

is renamed to `range()`

and original `range()`

function was removed.

So in simple terms, `xrange()`

is removed from Python 3, and we can use only the `range()`

function to produce the numbers within a given range.

**Use of range() and xrange()**

- In Python 2,
`range()`

returns the`list`

object, i.e., It does generate all numbers at once. The`range(1, 500)`

will generate a Python list of 499 integers in memory. So It consumes high memory and increases the execution time. `xrange()`

: The`xrange(1, 500)`

function doesn’t generate all numbers at once. It produces numbers one by one as the loop moves to the next number. So it consumes less memory and resources.

**Example**

```
print 'Python 2 range'
print range(10)
print type(range(10))
print 'Python 2 xrange'
for i in xrange(10):
print i
print type(xrange(10))
```

**Output**

Python 2 range() [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] type 'list' Python 2 xrange() 0 1 2 3 4 5 6 7 8 9 type 'xrange'

## Concatenating the result of two range()

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

. And you want the concatenated range like `[0, 1, 2, 3, 4, 10, 11, 12, 13, 14]`

.

For example, you want to add the result of two `range()`

functions to produce another sequence of numbers. You can add/merge the result of multiple `range()`

functions using `itertools.chin()`

.

```
from itertools import chain
# Concatenate ranges
new_range = chain(range(5), range(5, 10))
for num in new_range:
print(num, end=' ')
# Output 0 1 2 3 4 5 6 7 8 9
```

## range() indexing and slicing

Built-in function `range()`

is the constructor that returns a `range`

object, this range object can also be accessed by its index number using indexing and slicing.

**Access range() attributes**

It is essential to know the `range()`

attributes when you receive it as input to your function, and you wanted to see the value of the `start`

, `stop`

and `step`

argument.

```
range1 = range(0, 10)
# access range() attributes
print(range1.start) # 0
print(range1.stop) # 10
print(range1.step) # 1
```

**Indexing**

`range()`

supports both positive and negative indices. The below example demonstrates the same.

In the case of` range()`

, The index value starts from zero to (stop). For example, if you want to access the 3rd number, we need to use 2 as the index number.

```
range1 = range(0, 10)
# first number (start number) in range
print(range1[0])
# access 5th number in range
print(range1[5])
# Output 5
# access last number
print(range1[range1.stop - 1])
# Output 9
```

**Negative indexing**

The numbers can be accessed from right to left by using negative indexing.

```
# negative indexing
# access last number
print(range(10)[-1])
# Output 9
# access second last number
print(range(10)[-2])
# Output 8
```

**Slicing**

Slicing a implies accessing a portion from `range()`

```
# slicing
for i in range(10)[3:8]:
print(i, end=' ')
# output 3 4 5 6 7
```

## 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)
```

Is there a way to print a range of characters or alphabets? For example like this. It is possible to create a range of characters using the custom generator. Let’s see how to generate the ‘a’ to ‘z’ alphabet using the custom `range()`

function.

**Note**: We need to use the ASCII value and then convert the ASCII value to a letter using a `Chr()`

function.

```
# range from 'a' to 'z
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=', ')
```

**Output**

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,

## Summary

I want to hear from you. What do you think of this guide on Python range()? Let me know by leaving a comment below.

Also, try to solve the Python loop Exercise and for loop Quiz.

Below is the summary of all operations that we learned in this lesson

Operation | Description |
---|---|

`range(stop)` | Generate a sequence of integers from zero to stop-1 |

`range(start, stop)` | Generate a sequence of integers from start to stop-1 |

`range(start, stop, step)` | Generate a sequence of integers starting from the start number, increments by step, and stops before a stop number. I.e., Each next number is generated by adding the step value to a preceding number. |

`range(5, -1, -1)` | Reverse range |

`reversed(range(5))` | Reverse range using a `reversed()` function |

`range(-1, -11, -1)` | Negative range from -1 to -10 |

`list(range(2, 10, 2))` | Convert range() to list |

`range(start, stop+step, step)` | Generate an inclusive range |

`range(0, 10)[5]` | Access fifth number of a `range()` directly |

`range(10)[3:8]` | Slice a range to access numbers from index 3 to 8 |

`range.start` | Get the start value of a `range()` |

`range.stop` | Get the stop value of a `range()` |

`range.step` | Get the step value of a `range()` |

## FAQ

**Does range() in Python start at 0?**

The `range()`

by default starts at 0, not 1, if the start argument is not specified. For example, `range(5)`

will return 0, 1, 2, 3, 4.

**What does range() return in Python?**

The `range()`

function returns an object of class `range`

, which is nothing but a series of integer numbers.

**Is range a list in Python?**

No. `range()`

is not a list, nor it returns a list type. A `range()`

return `range`

object. You can verify the data type of `range()`

using the `type(range(5))`

function.

**How do you sum a range() in Python?**

Use bulit-in function sum(). For example, `sum(range(10)`