Mastering range()
in Python
The range()
function is one of the most commonly used tools in Python, especially when working with loops. It helps you generate a sequence of numbers, which is extremely useful when you want to iterate a specific number of times or generate indexes.
In this blog post, you'll learn how range()
works, its different forms, and how to use it effectively with practical, real-world examples.
What is range()
in Python?
The range()
function returns a special type of sequence that can be used in loops. It's most commonly used with for
loops, and it doesn’t generate all values at once — it’s a memory-efficient generator-like object.
Syntax
range(stop)
range(start, stop)
range(start, stop, step)
- start: Starting value of the sequence (default is 0)
- stop: End of the sequence (not inclusive)
- step: Difference between each number (default is 1)
Example 1: Using range(stop)
for i in range(5):
print(i)
This prints numbers from 0 to 4.
Example 2: Using range(start, stop)
for i in range(2, 6):
print(i)
This prints numbers from 2 to 5.
Example 3: Using range(start, stop, step)
for i in range(1, 10, 2):
print(i)
Prints odd numbers between 1 and 9.
Example 4: Reverse Counting with Negative Step
for i in range(5, 0, -1):
print(i)
Counts down from 5 to 1.
Example 5: Looping with Indexes
names = ["Amit", "Sara", "John"]
for i in range(len(names)):
print(i, names[i])
Loops through indexes to access list elements.
Example 6: Using range()
with sum()
total = sum(range(1, 6))
print("Total:", total)
Calculates the sum from 1 to 5.
Example 7: Create a List from range()
numbers = list(range(5))
print(numbers)
Converts the range into a full list.
Example 8: Skipping Multiples
for i in range(10):
if i % 3 == 0:
continue
print(i)
Skips numbers divisible by 3.
Example 9: Nested Loops with range()
for i in range(2):
for j in range(3):
print(i, j)
Useful for generating row-column patterns.
Example 10: Using range()
in a Condition
if 5 in range(10):
print("5 is within range")
Checks if a value is present in a range.
Why Use range()
?
- It’s simple and efficient for creating number sequences.
- Works perfectly with
for
loops. - Supports start, stop, and step to customize your sequence.
- Memory efficient: doesn’t store all values at once.
The range()
function is a fundamental tool for any Python programmer. Whether you're building a loop, generating numbers, or creating patterns, range()
is your go-to function.
Mastering range()
will help you write more powerful loops and develop cleaner, more efficient code in Python.