Python range() built-in function

From the Python 3 documentation

Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.

Basics

The range type is commonly used in for loops to loop a specific number of times. range takes in three parameters, start, stop and step. Each parameter must be intergers (either built-in int or any object that implements the index() special method).

If there is only one parameter, it represents the stop parameter. If the step parameter is omitted at all, it will default to 1. If the start parameter is omitted, it will default to 0.

Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices.

***The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents

Input Parameters:

Ranges implement all of the common sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern).

start:

  • The value of the start parameter
  • If not supplied, parameter will default to 0
  • Parameter value is inclusive

stop

  • The value of the stop parameter
  • The only parameter that is required
  • Parameter value is exclusive

step

  • The value of the step parameter
  • If not supplied, parameter will default to 1

Examples

Range with only stop parameter specified

>>> for i in range(5):
...     print(i)
# 0
# 1
# 2
# 3
# 4

Range with both start and stop parameters

>>> for i in range(1,8):
...     print(i)
# 1
# 2
# 3
# 4
# 5
# 6
# 7

Range with all parameters specified

>>> for i in range(0,30,5):
...     print(i)
# 0
# 5
# 10
# 15
# 20
# 25

Range with all parameters, where the stop parameter is not divisible by the step parameter

>>> for i in range(0,10,3):
...     print(i)
# 0
# 3
# 6
# 9

Range with all parameters, where the stop and step parameters are negative

>>> for i in range(0,-6,-1):
...     print(i)
# 0
# -1
# -2
# -3
# -4
# -5

Two examples where the stop parameter is set to 0

>>> for i in range(0):
...     print(i)
#
>>> for i in range(1,0):
...     print(i)
#

Subscribe to pythoncheatsheet.org

Join 10.900+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.