What it does
range() generates a sequence of integers. It's commonly used in for loops and to create lists of numbers. It doesn't create the full list in memory—it generates numbers on demand.
Basic usage
# range(stop) — 0 to stop-1:
for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4
# range(start, stop) — start to stop-1:
for i in range(2, 5):
print(i)
# Output: 2, 3, 4
# range(start, stop, step) — with step:
for i in range(0, 10, 2):
print(i)
# Output: 0, 2, 4, 6, 8
Creating lists
# Convert to list:
numbers = list(range(5))
print(numbers) # [0, 1, 2, 3, 4]
# Countdown:
countdown = list(range(5, 0, -1))
print(countdown) # [5, 4, 3, 2, 1]
Common patterns
# Loop N times:
for _ in range(10):
print("Hello")
# Loop with index:
items = ['a', 'b', 'c']
for i in range(len(items)):
print(i, items[i])
# Even numbers:
evens = list(range(0, 10, 2))
print(evens) # [0, 2, 4, 6, 8]
Important notes
range()doesn't include the stop value (it's exclusive)- It's memory-efficient (doesn't store all numbers)
- Use
list()to convert to a list if needed - Negative steps work for counting backwards