liveBook · Manning

Range

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

range() is a Python built-in that represents an arithmetic sequence of integers for iteration.

range() represents an arithmetic sequence of integers for iteration. Its stop value is excluded, and a single argument supplies a stop with an assumed start of 0. section 11.1.1

Use range() to:

  • Repeat an action a chosen number of times, using _ when the generated integer is irrelevant. section 9.3.5
  • Generate indexes for a sequence, such as character positions passed to random.sample(). section 10.1.3
  • Count upward or use a negative step to count downward; reversed(range(...)) provides another reverse-iteration option. section 11.1.1

Exclusive stop and reverse steps

list(range(5)) produces [0, 1, 2, 3, 4]. list(range(1, 5)) produces [1, 2, 3, 4], while list(range(5, 0, -1)) produces [5, 4, 3, 2, 1]. Swapping start and stop without a negative step produces an empty sequence. section 11.1.1

Iteration without using the values

num_insults = 2 for _ in range(num_insults): print('An insult!') This prints the line twice. The underscore documents that each generated value is intentionally discarded. section 9.3.5

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

Because this is a lazy function, we must use the list() function in the REPL to force it to produce the numbers. Remember that the stop value is never included in the output, so the preceding output stopped at 4, not 5.

Inspect the generated values and see the exclusive stop directly in a REPL-style example. section 11.1.1

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains arguments, exclusive bounds, lazy evaluation, throwaway variables, indexing, and reverse steps, but defers implementation internals.
Examples
Demonstrates repeated insults, character-index sampling, bottle-song countdowns, Christmas-day counting, and squared-number list comprehensions.
What it assumes
Assumes familiarity with integers, for loops, sequences, and basic function calls while reinforcing iteration patterns from concrete programs.
What you can do after
Apply it via Python loops, comprehensions, map(), indexing, and reverse counting with correctly chosen bounds and steps.
How it connects
Connects range() with for loops, list comprehensions, map(), reversed(), random.sample(), indexing, and test-driven development.

Also explained in

Compare how 8 books explain range →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.