range() creates a sequence of integers without storing them all in memory. It is commonly used with for.
The three forms#
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 6))) # [2, 3, 4, 5]
print(list(range(1, 10, 2))) # [1, 3, 5, 7, 9]
print(list(range(5, 0, -1))) # [5, 4, 3, 2, 1]- The stop value is excluded.
- The default start is 0.
- The default step is 1.
- A negative step counts down.
range() is lazy. list() materialises the values, which is useful for inspection but unnecessary in a loop.
Counting from one#
for position in range(1, 4):
print(f"Item {position}")Item 1 Item 2 Item 3
Do not add 1 inside the loop to make the output one-based if the loop variable only controls display. Start the range at 1 instead.
Summing with a step#
total = 0
for number in range(3, 31, 3):
total += number
print(total) # 165This adds 3, 6, 9, ..., 30.
enumerate()#
When you need both the index and the value, use enumerate() instead of manually maintaining a counter:
tasks = ["write", "test", "deploy"]
for index, task in enumerate(tasks):
print(index, task)0 write 1 test 2 deploy
Start numbering at 1 when presenting positions to people:
for position, task in enumerate(tasks, start=1):
print(f"{position}. {task}")zip()#
zip() combines parallel iterables:
names = ["Ada", "Grace", "Linus"]
scores = [90, 95, 88]
for name, score in zip(names, scores):
print(f"{name}: {score}")It stops at the shortest input. If you need to detect mismatched lengths, check them first.
range is not a list#
numbers = range(5)
print(numbers) # range(0, 5)
print(list(numbers)) # [0, 1, 2, 3, 4]
numbers[0] = 99 # TypeErrorA range supports indexing and length but is immutable.
Practice#
Print a 5-row number triangle using range(). Then print a numbered list of five fruits with enumerate(..., start=1). Finally, use zip() to pair each fruit with a price and print a simple receipt.
