From here to there — range()
The problem...
Your for loop knows how to move through a string. One character at a time.
But what if you don't have a string? What if you just need to repeat something ten times? Or count from 1 to 100?
You need a sequence of numbers. And you're not writing it by hand.
The idea!
range() generates a sequence of numbers on demand. No list. No manual counting. Just tell Python where to start and where to stop.
The syntax
range(stop)
range(start, stop)
range(start, stop, step)
Three forms. You'll use the first two most of the time.
range(stop)
for i in range(5):
print(i)
# 0
# 1
# 2
# 3
# 4
Starts at 0. Stops before 5. Always. Just like string indexing — Python counts from zero.
range(start, stop)
for i in range(1, 6):
print(i)
# 1
# 2
# 3
# 4
# 5
Now you control where it starts. Stop is still not included — range(1, 6) gives you 1 to 5.
range(start, stop, step)
for i in range(0, 10, 2):
print(i)
# 0
# 2
# 4
# 6
# 8
Step controls how much to jump each time. Default is 1 — but you can skip, count backwards, or jump by any amount.
Counting backwards
for i in range(5, 0, -1):
print(i)
# 5
# 4
# 3
# 2
# 1
Negative step — Python counts down. Useful for countdowns, reversals, and more.
Using range() with len()
word = "Bull"
for i in range(len(word)):
print(f"Index {i}: {word[i]}")
# Index 0: B
# Index 1: u
# Index 2: l
# Index 3: l
range(len(word)) gives you exactly as many numbers as there are characters. Now you have both the index and the character at the same time.
Heads up!
range(stop)starts at 0 — not 1- Stop is never included —
range(1, 6)gives 1, 2, 3, 4, 5 - Default step is 1 — use a negative step to count backwards
range()doesn't store numbers in memory — it generates them one at a time
The mindset shift
Stop thinking: "I need to write out every number."
Start thinking: "I tell Python the boundaries. It handles the sequence."
What you should understand now
range(stop)— generates 0 to stop-1range(start, stop)— generates start to stop-1range(start, stop, step)— jump by step each time- Stop is never included — range(1, 6) gives 1, 2, 3, 4, 5. Never 6.
range(len(word))gives you indexes to work with