Better Programming

Advice for programmers.

Follow publication

Member-only story

A Complete Guide to the Python Range Function

Chaitanya Baweja
Better Programming
Published in
5 min readJun 30, 2020

--

Photo by Kolleen Gladden on Unsplash.

Range is a built-in Python function that returns a sequence of numbers between a start integer (0 by default) and a stop integer.

We can iterate over the sequence generated by the range function using a for/while loop:

print("Getting a sequence of numbers between 0 and 10")
for i in range(10):
print(i, end =' ')

# Output
# Getting a sequence of numbers between 0 and 10
# 0 1 2 3 4 5 6 7 8 9
Photo by the author.

In this tutorial, we will learn how to use Python’s range() function with the help of different examples. Refer to the official documentation if necessary.

Syntax

range(start, stop, step_size)

Here:

  • start: Starting point of the sequence. Optional and by default 0.
  • stop: Ending point of the sequence. The sequence ends one element before stop.
  • step_size: Increment sequence by step_size. Optional and by default 1.

Range returns a sequence of numbers that begins at start and ends before stop. The difference between the elements is step_size.

Let’s take a closer look at all three possible variants of the range() function.

Variant 1: Using only one argument (stop)

Here, we only pass a stop argument (where to end) to the range function. start and step_size will take default values of 0 and 1, respectively:

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

Note: In the output above, the sequence ends an element before the stop value of 10. stop is not a part of this sequence.

Variant 2: Using two arguments (start and stop)

--

--

Chaitanya Baweja
Chaitanya Baweja

Written by Chaitanya Baweja

Machine Learning Engineer | Python | Data Analytics | Economics | Physics

Responses (2)

Write a response