range

The built-in range data type represents an immutable sequence of numbers, typically used for looping a specific number of times in for loops. It generates arithmetic progressions and is memory efficient as it computes the numbers lazily:

Python
>>> range(5)
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]

range(1, 10, 2)
>>> list(range(1, 10, 2))
[1, 3, 5, 7, 9]

range Constructors

Python Syntax
range(stop)
range(start, stop[, step])

Arguments

Argument Description Default Value
start The starting value of the range. 0
stop The end value of the range (exclusive). Required argument
step The difference between each pair of consecutive values in the range. 1

Return Value

  • Returns a Python range object

range Examples

Creating an empty instance of a range object results in a range with no elements:

Python
>>> range(0)
range(0, 0)

Creating ranges for specific intervals:

Python
>>> r = range(5)
>>> list(r)
[0, 1, 2, 3, 4]

>>> r = range(1, 7)
>>> list(r)
[1, 2, 3, 4, 5, 6]

>>> r = range(1, 20, 2)
>>> list(r)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Accessing values from a range through indexing:

Python
>>> r = range(10)
>>> r[2]
2
>>> r[-1]
9

range Methods

Method Description
.count(x) Returns the number of occurrences of x in the range.
.index(x) Returns the index of the first occurrence of x in the range.

range Common Use Cases

The most common use cases for the range include:

  • Looping a specific number of times in for loops
  • Generating sequences of numbers for iteration
  • Creating sequences of evenly spaced numbers

range Real-World Example

Say that you want to generate a sequence of numbers representing the leap years between 2000 and 2100:

Python
>>> leap_years = range(2000, 2100, 4)
>>> list(leap_years)
[
    2000, 2004, 2008, 2012, 2016,
    2020, 2024, 2028, 2032, 2036,
    2040, 2044, 2048, 2052, 2056,
    2060, 2064, 2068, 2072, 2076,
    2080, 2084, 2088, 2092, 2096
]

In this example, the range object helps efficiently generate a list of leap years by specifying the start, stop, and step values.

Tutorial

Python range(): Represent Numerical Ranges

Master the Python range() function and learn how it works under the hood. You most commonly use ranges in loops. In this tutorial, you'll learn how to iterate over ranges but also identify when there are better alternatives.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Dec. 6, 2024 • Reviewed by Dan Bader