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

**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])`

Code language: Python (python)

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`

.

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

.

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

.

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

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

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

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

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

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

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

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

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

returns a `range_iterator`

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

in the reverse order.

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

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

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.

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

the `start`

must be greater than `stop`

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

.

Also, you can use `step`

to generate sequence of numbers multiply of n.

Also, you will get a `valueerror`

if you set `step = 0`

.

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.

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.

**Combination of negative and positive numbers**

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

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

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

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

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

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

.

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

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

**Negative indexing**

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

**Slicing**

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

## range() over character or alphabet

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

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.

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