Python Range Type
What Is a Range?
A range object represents an immutable sequence of numbers, commonly used for looping a specific number of times in for loops. Ranges are memory-efficient because they only store the start, stop, and step values, not the entire sequence.
Creating Ranges
You can create a range using the range()
constructor:
r1 = range(5) # 0, 1, 2, 3, 4
r2 = range(1, 6) # 1, 2, 3, 4, 5
r3 = range(0, 10, 2) # 0, 2, 4, 6, 8
r4 = range(10, 0, -1) # 10, 9, 8, ..., 1
- The arguments are
start
,stop
, and optionalstep
(default is 1).
Accessing Range Values
You can convert a range to a list or tuple, or access items by index:
r = range(3, 8)
print(list(r)) # [3, 4, 5, 6, 7]
print(r[0]) # 3
print(r[-1]) # 7
print(r[1:4]) # range(4, 7)
print(list(r[1:4])) # [4, 5, 6]
Common Range Operations
Ranges support many sequence operations:
r = range(5)
print(len(r)) # 5
print(3 in r) # True
print(r.index(3)) # 3
print(r.count(2)) # 1
Iterating Over Ranges
Ranges are most often used in for loops:
for i in range(3):
print(i)
Range Attributes
Range objects have three attributes:
r = range(1, 10, 2)
print(r.start) # 1
print(r.stop) # 10
print(r.step) # 2
Comparing Ranges
Two ranges are equal if they represent the same sequence of values:
print(range(0, 3, 2) == range(0, 4, 2)) # True
Summary
- Ranges represent sequences of numbers, defined by start, stop, and step.
- Memory-efficient, even for large ranges.
- Support indexing, slicing, and sequence operations.
- Commonly used for looping a specific number of times.