Range Basics
Understanding Range in Python
In Python, the range()
function is a powerful tool for generating sequences of numbers. It provides an efficient way to create numeric sequences without storing the entire sequence in memory.
Basic Syntax
The range()
function supports three primary forms:
## Create a range from 0 to n-1
simple_range = range(5) ## 0, 1, 2, 3, 4
## Create a range with start and stop
custom_range = range(2, 7) ## 2, 3, 4, 5, 6
## Create a range with start, stop, and step
stepped_range = range(1, 10, 2) ## 1, 3, 5, 7, 9
Key Characteristics
Characteristic |
Description |
Memory Efficiency |
Generates values on-the-fly |
Immutable |
Cannot be modified after creation |
Indexable |
Supports indexing and slicing |
Range Behavior Flowchart
graph TD
A[range() Function] --> B{Number of Arguments}
B --> |1 Argument| C[Stop Value Only]
B --> |2 Arguments| D[Start and Stop]
B --> |3 Arguments| E[Start, Stop, Step]
C --> F[Starts from 0]
D --> G[Custom Start Point]
E --> H[Custom Increment]
Practical Examples
## Iterating with range
for i in range(5):
print(i) ## Prints 0, 1, 2, 3, 4
## Using range in list comprehension
squares = [x**2 for x in range(6)]
print(squares) ## [0, 1, 4, 9, 16, 25]
## Reverse range
for i in range(5, 0, -1):
print(i) ## Prints 5, 4, 3, 2, 1
range()
is more memory-efficient than creating full lists
- Ideal for loops and mathematical sequences
- Supports large ranges without consuming excessive memory
At LabEx, we recommend mastering range()
as a fundamental skill for Python programming.