Python 3.14 Β·
β verified by execution on 2026-07-22
The for loop in Python iterates over the items of any sequence.
python
words = ['cat', 'window', 'defenestrate']for w in words: print(w)
Output
cat
window
defenestrate
Your output
The range() Function
If you do need to iterate over a sequence of numbers, the built-in function, range() is the tool you need.
python
for i in range(3): print(i)
Output
0
1
2
Your output
Remember: The given end point is never part of the generated sequence. Thus, range(3) yields 0, 1, 2 but not 3.
Start, Stop, and Step
You can also choose where to start and how big each step is. The full form is range(start, stop, step) β start counting at start, stop beforestop, and jump by step each time.
python
for i in range(2, 8, 2): print(i)
Output
2
4
6
Your output
range(2, 8, 2) starts at 2, counts by 2, and stops before 8 β so 8 is never produced.
Try It Yourself
Drag the slider to change how many rows this loop prints, then press Run. Notice that range(n) always starts at 0, so n is exactly how many times the loop body runs.
python
drag to change the value, then Run
n = 5for i in range(n): print('*' * (i + 1))
Output
*
**
***
****
*****
Your output
Counting Backwards
You can even use a negative step to count backwards:
python
for i in range(0, -3, -1): print(i)
Output
0
-1
-2
Your output
Iterating with Indices
If you need both the index and the item, you can iterate over the indices of a sequence:
python
a = ['Mary', 'had', 'a', 'little', 'lamb']for i in range(len(a)): print(i, a[i])
Output
0 Mary
1 had
2 a
3 little
4 lamb
Your output
Common Misconceptions
A for loop in Python is like C where you define the initialization, condition, and increment.
Pythonβs for loop iterates over the items of any sequence in the order they appear.
range(5) generates numbers from 1 to 5.
range(5) generates numbers from 0 to 4 (the end point is exclusive).
Reading that and agreeing with it is easy. Predicting it under your own steam is
the part that sticks β so before you scroll, commit to an answer:
Predict the outputpython
Three loops, three ranges. Write down every line this prints, in order β and be careful with the third one.
for i in range(3): print(i)for i in range(3, 6): print(i)for i in range(6, 3): print("never runs")
Output
0
1
2
3
4
5
You predicted
If you wrote 1 2 3 for the first loop, or expected the third loop to count
downwards, you have just found the exact edge of what you knew β which is worth
more than getting it right.
Edge Cases
Empty sequences -> The loop body never executes.
range() with start equal to or greater than stop (with positive step) -> Generates empty sequence.
Under the Hood
Watch how the for loop dynamically assigns the next value from range() to the iteration variable on each cycle:
python Β· visualize
for i in range(2, 8, 2): print("Value:", i)print("Loop finished")
Check yourself
What numbers will `range(3)` generate?
Reveal answer
0, 1, 2 β range(stop) starts at 0 by default and ends before the stop value, making the end point exclusive.
How does Python's `for` loop differ from traditional C-style for loops?
Reveal answer
It directly iterates over the items of a sequence, rather than just counting numbers. β Python's for loop iterates over the items of any iterable (like a list or string) in the order they appear.
What does `range(2, 8, 2)` generate?
Reveal answer
2, 4, 6 β It starts at 2, increments by 2 (the step), and stops before it reaches 8.
Challenges
Challenge 1 +50 XP
Use a for loop and the `range()` function to print the numbers 1 through 5 (inclusive).
python
Test 1 β expects "1\n2\n3\n4\n5"
Need a hint? (β25% XP)
Use range(1, 6) since the stop value is exclusive.
Show solution (0 XP)
for i in range(1, 6): print(i)
Challenge 2 +100 XP
Iterate over the list `colors` and print each item.
python
Test 1 β expects "red\ngreen\nblue"
Need a hint? (β25% XP)
Use `for color in colors:`.
Show solution (0 XP)
colors = ['red', 'green', 'blue']for color in colors: print(color)
π Bug Hunt+75 XP
This code should print every colour in order. It runs without an error β and prints the wrong thing. Find the defect and fix it.
This code runs. It just does the wrong thing. Read it, find the defect,
fix it β the tests below decide when you are right.
python
Test 1 β expects "red\ngreen\nblue"
Need a hint? (β25% XP)
Negative indexes are legal in Python β they count from the end. What is colors[-1]?
Show solution (0 XP)
colors = ['red', 'green', 'blue']for i in range(len(colors)): print(colors[i])
Go deeper
Array or Linked List? Score the Workload, Not the Table β Everyone memorises the table - arrays index fast, linked lists insert fast - and still cannot pick one. Run both structures against the same operations here and watch the totals swap places depending only on what the code actually does.
Appending Is O(1) on Average, and the Average Hides the Interesting Part β Most appends to a list write one slot. Occasionally one copies the entire array. Change the growth strategy here and watch the spikes move - growing by a fixed amount stays quadratic however large the amount is.
Why Databases Use B-Trees: Fewer Levels Beats Fewer Comparisons β A balanced binary tree of a billion keys is thirty levels deep. If every level is a disk read, that is thirty reads for one lookup. Drag the branching factor here and watch the same keys collapse from a tall thin tree into a short wide one.
A Heap Is a Tree You Can Store in a Flat Array β Heaps are taught as trees and implemented as arrays, and the join between the two is usually three index formulas nobody explains. Watch a value sift up and down here, moving in the tree and the array at the same time, one swap per click.
List or Matrix? Guess Before You Look, and Watch the Answer Flip β Lists for sparse graphs, matrices for dense ones is true enough to repeat and too vague to use. Predict the winner here on two dials - density and question mix - and find out how often the rule of thumb is wrong.
Your Prompt Has 3,840 Right Answers, and It Picked One β Write a post about our launch is six words and not a request for one thing. Count the decisions it leaves open and the options multiply out to 3,840 different replies, every one of them a fair reading. Send it here, watch the model fill in your blanks, and see what specifying actually buys.
Trim or Summarise: The Cheap Fix That Makes Your Agent Forget Why It Is Here β An agent's context grows until something stops it, and there are two ways to stop it. On the same schedule they cost within 60 tokens of each other, and one of them ends the run having lost every fact the job depended on. Run twenty turns here and choose.
No Sorting Algorithm Wins. Look at Your Data First. β Insertion sort is not slow and quicksort is not fast - each is the cheapest choice for some shape of input and the dearest for another. Predict the winner across five shapes here and watch a single favourite fail.
Find the Wasted Calls: the Skill Behind Every Memoisation β Memoisation is easy to explain and hard to apply, because the difficult part is noticing that a subproblem repeats at all. Here the recursion tree is drawn and you have to find the repeats yourself, scored, with wrong clicks counted.