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.
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
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.
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
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)hasb - a, which makes slicing math and loops easy to reason about. - To count down, use a negative step and make
startlarger thanstop:range(10, 0, -1)goes 10 down to 1. With a positive step andstart >= stopthe range is empty. - It is lazy. Convert with
list(range(...))only when you need an actual list. Loops,sum(),inandlen()work directly. - Fast membership.
x in range(...)is computed arithmetically in constant time for integers, not by scanning. - Supports indexing, slicing,
len,indexandcount, and slicing returns anotherrange. It does not support item assignment,appendor concatenation. - No float steps. Use a loop with multiplication,
numpy.arangeornumpy.linspacefor fractional steps. - Looping over a list by index is usually a smell: prefer
for item in itemsorenumerate(items). - Equality compares the sequences, so ranges with different arguments can be equal when they produce the same numbers.
- Python 2's
xrangeis today'srange; the old list-buildingrangeno longer exists.
Related
enumerate(),reversed(),zip(),slice(),list()- The range object
- Lessons: Range, For loops, Slicing