Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.4 — for Loops and range()
Python · Example 2 of 2

range is lazy, and empty ranges

A billion-number range answers instantly because Python never builds it. Try len(range(0, 10, 3)) and predict it.

A for loop visits each item of a sequence one by one, and range(start, stop, step) produces the numbers for counting loops. range stops before stop and is lazy: it never builds the whole list in memory.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Print the squares of 1 to 5, one per line, with a for loop and range.

02

Add up the even numbers from 2 to 20 and print Total: 110.

03

Print a countdown 10, 7, 4, 1 using range with a negative step.

04

Count how many vowels (a, e, i, o, u) are in the text "education" and print Vowels: 5.

Explain it without notes

01

Explain what range(2, 10, 3) produces and why 10 does not appear.

02

What is an off-by-one error? Give an example with range.

03

Why is range(1_000_000_000) cheap, and how do you see its numbers?

04

What does a for loop do when the collection is empty?

range is lazy, and empty ranges
Sign in to run this example in your browser.

Expected output

range(0, 1000000000)
1000000000
True
3 999999999
[]
[]
5
k after the loop: 2