Understanding Python Ranges and How They Control Loops

Ranges play a major role in controlling how loops run. A range defines a sequence of numbers. Instead of writing numbers by hand, you let Python generate them for you. This keeps code short and readable.

Understanding What a Range Is

A range is created using the range() function. It does not store numbers in memory like a list. Instead, it represents a sequence that Python can navigate when needed.

Ranges are most often used with for loops. This pairing is common because it allows you to control the number of times a loop runs. When Python encounters a range in a loop, it iterates through the range, pulling one number at a time and assigning it to the loop variable.

You can consider a range inside a loop as a counter generator. Each pass through the loop moves to the next number. When the sequence ends, the loop stops.

The most basic form takes one value. That value tells Python where to stop.

Code creates a sequence of numbers ranging from 0 to 2. The number 3 is excluded because the stop argument does not include it.

The sequence always starts at zero unless told otherwise.

Example of generating a sequence of integers between 2 and 6.

Customizing the Range

Ranges become more useful when you add more control. You can set a start value, an end value, and even a step size. This allows you to count forward, count backward, or skip values. For example, you can count down instead of up.

Counting backwards using a negative step value.

Or loop through only even numbers:

Using the step value in range() to skip odd numbers.

The only required argument for the range() function is the stop argument.

range(start, stop, step)

If you don’t provide any arguments to range(), then you’ll get a TypeError:

Providing no arguments to range(), initiates a TypeError.

Conclusion

Ranges help keep loops predictable and safe. You can determine precisely how many times the loop will run. This is helpful when processing data or repeating tasks. Ranges help you write simpler loops.

Although my blog doesn’t support comments, feel free to reply via email or X.