How to Use Range in Python

Written by Coursera • Updated on

By the end of this tutorial, you will be able to use Python range to generate and iterate through sequences.

[Featured Image] Someone works with Python range on a laptop at a desk with a second monitor.

Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE) of your choice (or terminal), stable internet connection

Prerequisites/helpful expertise: Basic knowledge of Python and programming concepts

Range is a control flow tool, and one of Python’s built-in functions. It enables us to generate number sequences. When combined with loops, we can also use range() to iterate through these sequences.

Glossary

TermDefinition
SyntaxIn programming, syntax is the set of rules that defines the structure of a language.
Printprint() is a function that converts a specified object into text and sends it to the screen or other standard output device.
IterablesIterables are objects in Python that you can iterate over.
IndexIndexing in Python refers to accessing specific objects within an iterable by their position.
FunctionA function is a block of code that will only run when it is called upon.
For loopAn iterating function used to execute statements repeatedly.
IterateIn programming, iteration is the repetition of a code or a process over and over until a specific condition is met.
ConcatenateConcatenation is the joining of two or more strings in Python. The strings are merged end-to-end, creating a new string.
Floating-point numbersAny number that has a decimal place is a floating point number (or, a float.)
range()Python range() is a function that returns a sequence of numbers.

What does range do in Python?

In Python, the range() function returns a sequence of numbers. By default, Python follows these rules when defining the sequence:

  • It begins with 0.
  • It advances in increments of 1.
  • It does not include the final number in the specified range. You can change the parameters of your range if the default settings don’t suit your needs.

Range parameters

There are three parameter values for the range() function: 1. Start: Optional. If you don’t want to use the default 0, use this parameter to specify which integer number will start the sequence.

2. Stop: Required. Use this parameter to specify which integer number will stop the sequence.

3. Step: Optional. Use this number to specify the incrementation or decrementation of your sequence, if not a positive 1 (default).

Reminder

The range function is not inclusive in Python. By default, range does not include the last value.

Range syntax

PYTHON
1
range(start, stop, step)

Can I use floating point or non integer numbers?

Python range does not support the float type, it only works with integers.

How to use range in Python (with examples)

Since two of the three parameters for Python range() are optional, there are several different ways to use this function. First, let’s examine how to use it with the required parameters only.

With stop argument

Stop is the only required parameter because it tells Python which integer number will end the sequence. For example, suppose you want the range to start at 0 and stop at 5 (not including 5). In that case, your code might look like this: Screenshot 2023-02-23 at 12.47.22 PM

If you want to include 5 in your iteration, your code would look like this instead: Screenshot 2023-02-23 at 12.48.49 PM

Reminder

If you only pass a single argument to range, it will be passed as the stop argument.

With start and stop arguments

Start is not a required parameter. However, you will need to use it when starting your sequence with any integer number other than 0. Here’s an example with 1 as the start argument and 10 as the stop argument (10 included): Screenshot 2023-02-23 at 12.51.19 PM

Try it yourself

Use start and stop arguments with range() to return a sequence that starts at 5 and ends at 10 (exclusive).


PYTHON
1
2
for num in range(5, 10):
  print(num)

With start, stop, and step arguments

Step is another optional parameter. It is useful for creating sequences that take steps larger or smaller than the default 1. You can also use it to print odd numbers or even numbers only. You have two options when choosing a custom step value:

1. Positive step
Any positive integer number you enter in the step value will result in an incrementation.

Example: Screenshot 2023-02-23 at 12.56.43 PM

In the example above, the sequence starts at 1, stops at 14, and increments in steps of 3.

2. Negative step
If you want to decrement, your step must be a negative value.

Example: Screenshot 2023-02-23 at 12.59.25 PM

In the example above, the sequence starts at 10, ends at 0, and increments in steps of -2.

What happens if you use 0 as a step value?

Your range must increment or decrement. A 0 step value will result in a ValueError.

Try it yourself

Use start, stop, and step arguments with range() to write a program that returns 100, 75, 50, 25.



PYTHON
1
2
for num in range(100, 0, -25):
  print(num)

To get the required output, you'd need to set your start value to 100, your stop value to 0, and your step argument to -25.

Tip

Using a negative step in range lets you iterate through a decrementing series. If you want to loop over the series in reverse order, you can use Python’s built-in reversed() function.

How to loop with range

Python range returns an object consisting of the series of integer numbers you specify. As we've already seen, you can iterate through this using a for loop. You can see how this works in the examples above.

How to define a list with the range

Although range objects behave like lists, they are not lists. A range object saves space by returning the items of your desired sequence without creating a list. Nonetheless, you can still use Python range to create a list using the list() function.

Example: Screenshot 2023-02-23 at 1.17.09 PM

You can also use the * operator to create a list from a range() object in Python. The * operator, sometimes called the "splat" operator or the "unpacking" operator, can be used to unpack the elements of a sequence object like a range() object into a new list.

Example: Screenshot 2023-02-23 at 1.21.42 PM

Tip

Python uses a programming strategy called lazy evaluation. In other words, it won’t produce certain objects until they are needed. Lazy evaluation helps code run more efficiently by discarding sub-expressions that aren’t linked directly to the expression’s final result.

How index with range

You can use index with Python range to get the value at a specified position. For example, suppose you’re working with range(2, 10, 2). If you were to iterate through the range and print each value, your output will look like this: Screenshot 2023-02-23 at 2.04.17 PM

Here’s how to access the first value in the range: Screenshot 2023-02-23 at 2.05.35 PM

Any subsequent values can be accessed in the same way: Screenshot 2023-02-23 at 2.08.42 PM

Try it yourself

How would you access the third value in this range? Can you guess the value?

PYTHON
1
my_range = range(1,100,15)

PYTHON
1
2
3
my_range = range(1,100,15)

my_range[2]

Since Python indexes from the 0 position, the third value would be in the second position and would be 31.

Key takeaways

  • Python range is a function that returns a sequence of numbers.
  • By default, range returns a sequence that begins at 0 and increments in steps of 1.
  • The range function only works with integers. Other data types like float numbers cannot be used.
  • There are three range parameters: start, stop, and step. Only stop is required.
  • Range is not an inclusive function.
  • You can use positive and negative steps.

Resources

Keep improving your Python skills with Coursera.

You can practice working with for loops with a Guided Project like Concepts in Python: Loops, Functions, and Returns. Or, take the next step in mastering the Python language and earn a certificate from the University of Michigan in Python 3 programming.


Written by Coursera • Updated on

This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.

Learn without limits