Skip to main content

range() is a built-in function that gives you an immutable sequence of numbers, and its most common job is making a loop run a set number of times.

The sequence belongs to a data type of its own, named range.

Note: Something immutable stays exactly as it was created; it cannot be modified later.


Creating ranges

You can pass range() 1, 2 or 3 arguments. The full syntax looks like this:

main.py
range(start, stop, step)

Call range() With One Argument

A single argument is treated as the stop value.

Leave out start, which is optional, and counting begins at 0 by default.

So range(10) produces the numbers 0 through 9: the start value 0 is included, while the stop value 10 is not.

main.py
x = range(10)

Call range() With Two Arguments

With two arguments, the first is the start value and the second is the stop value.

So range(3, 10) produces the numbers 3 through 9:

main.py
x = range(3, 10)

Call range() With Three Arguments

A third argument sets the step value.

The step is the gap between one number and the next. You can leave it out, and then it is 1 by default.

So range(3, 10, 2) counts from 3 up to 9 in steps of 2:

main.py
x = range(3, 10, 2)

Using ranges

A very common place to find a range is a for loop, which walks through its numbers one by one.

Example

Print each number in a range:

Prompt
Write a Python program that uses a for loop with range(10) to print each number from 0 to 9.
Output: complete Python program

Using List to Display Ranges

A range object is its own immutable number sequence, and printing one does not list its numbers.

To see them, people usually turn the range into a list first.

Example

Turn a few different ranges into lists:

Prompt
Write a Python program that converts three different ranges to lists and prints them: range(5), range(1, 6), and range(5, 20, 3).
Output: complete Python program

Slicing Ranges

As with other sequences, you can slice a range to pull out part of it.

Note: In this example, the first print shows the value at index 2, and the second shows a new range object covering indexes 0 to 3.

Example

Pull a piece out of a range:

Prompt
Write a Python program that creates a range(10), prints the element at index 2, and prints a slice from index 0 to 3.
Output: complete Python program

Membership Testing

The in operator lets you test whether a range contains a number.

You get True if the number is in the range and False if it isn't.

Example

Find out whether 6 and 7 belong to a range:

Prompt
Write a Python program that creates range(0, 10, 2) and tests membership of 6 and 7 using the in operator. Print the results.
Output: complete Python program

Length

Pass a range to the len() function and it tells you how many elements the range has.

Example

Count the elements of a range:

Prompt
Write a Python program that creates range(0, 10, 2) and prints its length using len().
Output: complete Python program