range() with step

The third argument, counting backwards, and why the stop value is never one of the numbers you get.

Overview

The third argument, counting backwards, and why the stop value is never one of the numbers you get.

In this guide
  1. The three forms
  2. The stop is never included
  3. Counting down
  4. It does not build a list
  5. Only integers
  6. Counting backwards correctly
  7. When you want to walk something backwards
  8. range is not a list
  9. Slicing shares the same idea
  10. Why the stop is excluded, and why it is the right choice
  11. Chunking, the most common use of a step
  12. Floats, and stepping by a fraction
  13. The range(len(...)) habit, and what to write instead
  14. Reading a range at a glance
  15. Questions people ask about range() with step
  16. range() with step: recap in one screen

range_step.py

range_step.py Python 3
Output

                    

range_reverse.py

range_reverse.py Python 3
Output

                    

Worth knowing

Three arguments: range(start, stop, step). With one, it is the stop.
The stop is never produced. range(5) ends at 4.
Counting down needs a negative step and a stop below the start; to reach index 0, stop at -1.
reversed(x) or x[::-1] usually reads better than a backwards range.

range() with step: A Practical Guide

range takes up to three args. Start, stop and step. And makes numbers without ever building a list. The two things worth internalising are that the stop is excluded. What that means when counting down.

The three forms

range(5)         # 0 1 2 3 4
range(2, 6)      # 2 3 4 5
range(0, 10, 2)  # 0 2 4 6 8

One argument is the stop. Two are start and stop. Three add the step. The step can be any nonzero integer.

The range function generates a sequence of integers without building a list. It produces values one at a time as you loop over them. That makes it memory-efficient: range(1_000_000) uses the same amount of memory as range(10). Only the boundaries and the step are stored, not a million numbers.

The simplest form, range(n), counts from zero up to but not including n. This matches Python's indexing, where the first element of a list is at position zero. It also means that range(len(some_list)) produces every valid index for that list, though enumerate is usually a better choice.

The two-argument form, range(start, stop), lets you begin counting from a number other than zero. The stop value is still excluded. range(3, 7) gives 3, 4, 5, 6. The exclusion of the stop value is a deliberate design choice: it means range(a, b) has exactly b - a elements, and adjacent ranges like range(0, 5) and range(5, 10) cover the full span without overlap.

The three-argument form adds a step. range(0, 10, 2) counts by twos. range(1, 10, 3) gives 1, 4, 7. A negative step counts downward: range(10, 0, -1) gives 10 down to 1. A negative step with a start smaller than the stop produces an empty range. The step cannot be zero; that raises a ValueError.

A common use of the step parameter is iterating over every other element, counting backward through a sequence, or generating indices at regular intervals. Combined with slicing, it gives you control over exactly which positions a loop visits.

This page covers the three forms of range, why the stop is excluded, negative steps for counting down, and common patterns for using the step parameter.

The stop is never included

range(5) gives five numbers ending at 4. This looks like an off-by-one waiting to happen and is the opposite. It's what makes range(len(items)) give just the valid indices of a list. What makes range(a, b) give b - a numbers.

Counting down

Two things must both be true:

range(5, 0, -1)    # 5 4 3 2 1

The step is minus and the stop is below the start. Get one wrong and you get an empty range, not an error. range(5, 0) with no step makes nothing at all. It's counting up from 5 to 0.

The classic mistake is stopping at 0 when you meant to include it:

range(3, 0, -1)   # 3 2 1  - misses 0
range(3, -1, -1)  # 3 2 1 0

To walk a list backwards by index you need range(len(items) - 1, -1, -1). This Is three fiddly numbers in a row and just why the options exist:

for x in reversed(items):
for x in items[::-1]:

Both say "backwards" without math. Reach for a backwards range only when you truly need the index.

It does not build a list

range(1_000_000) stores three ints — start, stop, step — and finds each value on demand. It's a few dozen bytes what the size. This The page prints beside the list version for contrast.

That laziness is also why x in range(n) is fast. It does math rather than searching. It's the one in test on a sequence that doesn't scan.

Only integers

range refuses floats. For a fractional step, build the ints and divide, or use a library. range(0, 1, 0.1) is a TypeError, not a rounding problem.

Counting backwards correctly

A minus step is where range trips people, and the stop value is still exclusive. Counting down to and including zero means stopping at -1:

range(3, -1, -1)      # 3 2 1 0
range(3, 0, -1)       # 3 2 1   - zero is missed

The rule hasn't changed - range never includes its stop - but with a descending sequence the exclusive end is below the last value you want rather than above it, which is just the sort of thing that reads right and behaves or else.

An empty range isn't an error. range(0, 5, -1) makes nothing at all, because the start is already past the stop in the direction of travel. A loop over it runs zero times and says nothing. A wrong sign shows up as "the loop didn't happen" rather than as an exception.

When you want to walk something backwards

For iterating a sequence in reverse, reversed() says what it means and needs no math:

for item in reversed(items):

items[::-1] also works and builds a reversed copy first, so it costs memory proportional to the sequence. range(len(items) - 1, -1, -1) works too and is the version most likely to hold an off-by-one. Prefer reversed unless you in detail need the indices.

range is not a list

range(10_000_000) is instant and takes a few dozen bytes, because it stores only start, stop and step and finds each value on demand. This is why it can be huge, and why printing one shows range(0, 10) rather than the numbers.

It isn't a gen, though - it can be iterated again and again, it knows its own length, it supports indexing, and x in range(...) is a fast math check rather than a scan. That combination makes it more handy than a plain gen and cheaper than a list.

Slicing shares the same idea

The third arg to a slice is the same step, with the same rules, which is why [::2] takes each second item and [::-1] reverses. Learning the action once covers both, and the exclusive-stop rule is what makes a[:n] and a[n:] fit together with no gap and no share.

Why the stop is excluded, and why it is the right choice

"The stop is never included" is easy to store and easy to resent. It's worth a paragraph on why the language chose it. Once the thinking is clear the off-by-one errors mostly stop.

A half-open interval — one that includes the start and excludes the stop — has three properties that a closed interval doesn't. The length is the subtraction: range(a, b) makes just b - a numbers, with no correction term to note. The empty case is expressible: range(3, 3) is empty, where a closed interval would have no way to say "nothing" without a special case. And adjacent ranges join without a gap and without an share: range(0, 5) and range(5, 10) between them cover 0 to 9, each number just once, which is what makes splitting work.

The same choice runs through slicing. This Is why a[:3] and a[3:] rebuild the whole list and why len(a[i:j]) is j - i. Learning it once covers both, and the pattern is deliberate rather than accidental.

The place it still catches people is counting down. Here The exclusive end is below the last value you want rather than above it. That isn't a different rule, but it does read differently. This Is why it deserves its own focus.

Chunking, the most common use of a step

The step exists for a exact job more often than for skipping numbers: walking a sequence in fixed-size pieces.

items = list("abcdefgh")
size = 3

for i in range(0, len(items), size):
    print(items[i:i + size])
['a', 'b', 'c']
['d', 'e', 'f']
['g', 'h']

The last chunk is short and needs no special handling, because slicing doesn't complain when the end is past the length. That is the second time on this page that a rule which looks like leniency turns out to drop a branch.

This shape appears when a thing has a batch limit: rows to insert per query, items per API request, lines per page. The option is an index and a counter, which is more code and more places to be wrong by one.

Floats, and stepping by a fraction

range(0, 1, 0.1) raises TypeError. This Reads like a limitation and is closer to a favour. a fractional step builds up error:

x, vals = 0.0, []
while x < 1.0:
    vals.append(x)
    x += 0.1

print(len(vals), vals[-1])
11 0.9999999999999999

Eleven values, where the obvious reading of the loop promises ten, and the last isn't 0.9. Adding 0.1 again and again compounds the tiny error in showing 0.1 in binary, and after ten additions the running total is a hair under 1.0 — so the rule holds one more time than intended. The number of iterations now depends on rounding error rather than on any of it you wrote.

The solid pattern is to count in ints and divide once at the end:

print([i / 10 for i in range(0, 10, 2)])
[0.0, 0.2, 0.4, 0.6, 0.8]

Each value is found from an exact int rather than from the previous value, so no error builds up and the number of items is fixed by the range. For any of it more involved, numpy.arange and numpy.linspace exist, and linspace is the one to prefer because you give it the count rather than the step.

The range(len(...)) habit, and what to write instead

A large share of the range calls in beginner code are range(len(items)), used to get at the items:

for i in range(len(items)):
    print(items[i])

This works and is worth unlearning. It adds an index that nothing needs, it reads as math rather than as iteration, and it's the version that makes IndexError when the bound is found slightly wrong. for item in items says the same thing with less to get wrong.

The three cases that look like they need it often don't. If you want the spot alongside the item, enumerate(items) gives both. If you're walking two sequences together, zip(a, b) pairs them. If you're checking each item with the next, zip(items, items[1:]) gives back to back pairs.

What is left is truly index-based work: writing into a list at a found spot, stepping by more than one, or walking backwards by index. Those are real, and they're a small minority.

Reading a range at a glance

Three questions come up constantly when reading someone else's loop, and all three have math answers that are worth being able to do without running any of it.

How many numbers is that? For a plus step, it's the distance cut by the step, rounded up: range(0, 10, 3) covers a distance of 10 in steps of 3, giving 4 numbers. The rounding up is what catches people, and it's why range(0, 10, 3) gives four values rather than three.

What is the last one? It's the largest value below the stop that you can reach from the start by whole steps. For range(0, 10, 3) that is 9. When the step cuts the distance just, as in range(0, 10, 2), the last value is the stop minus the step. 8, not 10 — because the stop itself is never included.

Does it give any of it at all? Only if the start is on the correct side of the stop for the direction of travel. Ascending needs start < stop, descending needs start > stop. Neither raises when it's wrong. You get an empty range, and a loop that silently does nothing.

That last one is worth dwelling on. It's the failure mode that costs the most time. An exception tells you where to look. A loop that runs zero times leaves no trace at all, and the symptom appears later as an empty result or an unchanged variable. When a loop appears not to have happened, printing list(the_range) is often a faster diagnosis than reading the math again.

Questions people ask about range() with step

Why does range(5, 0) give nothing? Because the default step is 1, so it's counting up from 5 towards 0 and stops right away. You need range(5, 0, -1).

Is range a gen? No. It's a lazy sequence: it can be iterated many times, it has a length, and it supports indexing and slicing. A gen has none of those.

How do I get a list from a range? list(range(5)). It's worth asking whether you need one — a loop doesn't.

Why is x in range(n) fast? It does math rather than scanning, so it's constant time even so of the size of the range.

Can the step be minus and the start below the stop? It can be written, and it makes an empty range. Nothing is raised.

Does range work with very large numbers? Yes. range(10**18) is created instantly, because nothing is stored but the three values.

How do I include the stop? Add one to it. That is the honest answer, and range(1, n + 1) is how you count from 1 to n.

Can I slice a range? Yes, and you get another range back: range(10)[2:5] is range(2, 5). Nothing is materialised.

Why does range compare equal to another range with different args? Because ranges compare by the sequence they give, not by their start, stop and step. range(0) == range(2, 2) is True. Both are empty.

Is there a version that includes the stop? Not in the standard library. numpy.linspace is the closest, and it takes a count rather than a step, which sidesteps the question.

What does a minus index do on a range? The same as on any sequence: range(10)[-1] is 9. It's found rather than looked up, so it's instant even on an huge range.

Should I ever store a range in a variable? Yes, when the same sequence of numbers is used twice. Unlike a gen it can be iterated again, so it's safe to reuse.

range() with step: recap in one screen

  • One arg is stop, two are start and stop, three add a step. The stop is always excluded.
  • The half-open interval makes the length a subtraction, lets ranges be empty, and lets adjacent ranges tile without gaps.
  • Counting down needs both a minus step and a stop below the start, and a wrong sign gives an empty range rather than an error.
  • range refuses floats on purpose. Count in ints and divide once.
  • range(len(items)) is often enumerate, zip, or just iterating the items.

Check yourself

0 of 3

Answer without scrolling back up.

  1. What does `list(range(5, 0))` give?

  2. To walk indices of a 4-item list backwards including 0, you need:

  3. Why is `999_999 in range(1_000_000)` fast?

Cheat sheet

range() with step

Generate number sequences with range using start, stop and step, and see why range produces values lazily instead of building a list.

PYTHON · vizlearn.in/python/range_step.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.