Python Reference ยท Lists, Tuples and Ranges
The range object
Reference for the Python range object: start, stop and step attributes, len, membership tests, indexing, slicing, reversing and why it uses constant memory.
A range is an immutable sequence of integers described by three numbers: start, stop and step. It does not store its items. It computes each one when needed, so range(10**12) takes the same small amount of memory as range(3).
This page covers what a range object can do after you create it. For the constructor itself see range(). A range supports len(), indexing, slicing, in, count(), index() and iteration, and it can be iterated as many times as you like.
r = range(2, 20, 4) print(list(r), len(r)) # [2, 6, 10, 14, 18] 5
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.
Attributes and operations
| Feature | Behavior |
|---|---|
start, stop, step |
Read-only attributes. start defaults to 0 and step to 1. |
len(r) |
Number of items. Raises OverflowError if the length does not fit in a C ssize_t. |
r[i] |
The item at index i; negative indexes count from the end. Raises IndexError when out of range. |
r[a:b:c] |
A new range, not a list. |
x in r |
For ints, answered by arithmetic in constant time. Other types fall back to a slower comparison. |
r.index(x) |
Position of x; raises ValueError if absent. |
r.count(x) |
1 if present, else 0, because ranges have no repeated values. |
reversed(r) |
A lazy iterator going backward. |
Usage notes
- Stop is excluded.
range(1, 4)is 1, 2, 3. - Integers only. Floats raise
TypeError. For fractional steps use a comprehension or NumPy'sarange(). - Step cannot be 0. That raises
ValueError. A negative step counts down, and thenstartshould be larger thanstop. - Empty ranges are valid:
range(5, 5)orrange(1, 5, -1). All empty ranges compare equal. - Equality compares the sequences, not the arguments, so differently written ranges with the same items are equal.
- Not a list. Adding, concatenating and
append()are not supported. Uselist(r)when you need a list. - Printing a range shows its arguments (
range(0, 5)), not its items. - Very large values work because Python ints have no fixed size.
- A range is hashable and can be a dictionary key.
- Look-ups are fast:
in, indexing andlen()take constant time, unlike a list.
Related
range(),enumerate(),reversed(),list, slicing- Lessons: The range function, For loops