Python Range 📏
Generating Sequences
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
✨ Basic Usage
python
# range(stop)
for x in range(6):
print(x) # 0, 1, 2, 3, 4, 5🔢 Start, Stop, Step
You can customize the range with start, stop, and step parameters.
python
# range(start, stop)
for x in range(2, 6):
print(x) # 2, 3, 4, 5
# range(start, stop, step)
for x in range(2, 30, 3):
print(x) # 2, 5, 8, 11, ...🔙 Negative Steps
You can count backwards by using a negative step value.
python
for x in range(10, 0, -1):
print(x)
# Output: 10, 9, 8, ..., 1✨ Pro Tip: Lazy Evaluation
The range() function returns a "range object", not a list. It generates numbers on demand, which is very memory efficient. If you need a real list, convert it:
python
x = range(1000000) # Takes almost no memory
y = list(range(1000000)) # Takes memory for 1M integers