← Back to Articles
Tutorial

Understanding the Python Range Function

Learn all about Python's range function, its syntax, examples, and common pitfalls.

The Python range function is a key tool in generating a sequence of numbers. Whether you're iterating over a list or creating a loop, understanding range is crucial.

The range function generates a sequence of numbers, starting from a specified start value, up to, but not including, an end value. For example, range(0, 5) produces numbers 0 to 4.

When using the range function, ensure that you specify the correct start, stop, and step values. This helps in creating efficient loops and avoiding off-by-one errors.

A common mistake with range is forgetting that the stop value is not included in the sequence. Always remember that range(start, stop) includes start but excludes stop.

Code Examples

Example 1

for i in range(5): print(i)

Example 2

for i in range(1, 10, 2): print(i)

More Python Tutorials