Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python range() function

Reference for Python range(): generate integer sequences with start, stop and step, count backward, index and slice ranges and understand why they are lazy.

range is an immutable sequence type that represents an arithmetic progression of integers. range(5) stands for 0, 1, 2, 3, 4. It does not store its numbers: it stores only start, stop and step, and computes values on demand, so range(10**9) takes as little memory as range(3).

Its most common use is driving a for loop a fixed number of times. The stop value is always excluded.

Python
list(range(5))         # [0, 1, 2, 3, 4]
list(range(2, 10, 3))  # [2, 5, 8]
list(range(5, 0, -1))  # [5, 4, 3, 2, 1]

Try it

Python Start, stop and step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python A range is a real sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
range(stop)
range(start, stop)
range(start, stop, step)
Name Description
start First number. Default 0.
stop Where to stop; this number is not included.
step Difference between numbers. Default 1. May be negative, never zero.

All arguments must be integers (or objects with __index__()).

Return value: a range object.

Raises: TypeError for floats or other non-integers; ValueError if step is 0.

Usage notes

  • Stop is excluded. range(5) has five numbers, range(a, b) has b - a, which makes slicing math and loops easy to reason about.
  • To count down, use a negative step and make start larger than stop: range(10, 0, -1) goes 10 down to 1. With a positive step and start >= stop the range is empty.
  • It is lazy. Convert with list(range(...)) only when you need an actual list. Loops, sum(), in and len() work directly.
  • Fast membership. x in range(...) is computed arithmetically in constant time for integers, not by scanning.
  • Supports indexing, slicing, len, index and count, and slicing returns another range. It does not support item assignment, append or concatenation.
  • No float steps. Use a loop with multiplication, numpy.arange or numpy.linspace for fractional steps.
  • Looping over a list by index is usually a smell: prefer for item in items or enumerate(items).
  • Equality compares the sequences, so ranges with different arguments can be equal when they produce the same numbers.
  • Python 2's xrange is today's range; the old list-building range no longer exists.