Range Fundamentals
Introduction to Range
In Python, the range()
function is a powerful built-in method for generating sequences of numbers. It provides an efficient way to create numeric sequences without storing the entire sequence in memory, making it ideal for iteration and loop operations.
Basic Syntax
The range()
function supports three primary forms of initialization:
## 1. Single argument: range(stop)
for i in range(5):
print(i) ## Generates 0, 1, 2, 3, 4
## 2. Two arguments: range(start, stop)
for i in range(2, 7):
print(i) ## Generates 2, 3, 4, 5, 6
## 3. Three arguments: range(start, stop, step)
for i in range(1, 10, 2):
print(i) ## Generates 1, 3, 5, 7, 9
Key Characteristics
Characteristic |
Description |
Memory Efficiency |
Creates a sequence generator, not a list |
Immutable |
Cannot be modified after creation |
Supports Negative Steps |
Can generate descending sequences |
Advanced Range Techniques
graph LR
A[range() Function] --> B[Single Argument]
A --> C[Two Arguments]
A --> D[Three Arguments]
B --> E[Default Start: 0]
C --> F[Custom Start/Stop]
D --> G[Custom Start/Stop/Step]
Practical Examples
Reverse Iteration
## Descending sequence
for i in range(10, 0, -1):
print(i) ## Generates 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
List Conversion
## Converting range to list
numbers = list(range(5))
print(numbers) ## [0, 1, 2, 3, 4]
The range()
function is memory-efficient because it generates values on-the-fly, which is particularly useful when working with large sequences in LabEx programming environments.
Common Pitfalls
- Remember that
range()
is exclusive of the stop value
- Negative steps require start > stop
- Always ensure step value is non-zero