Skip to main content

4.7 - Working With Ranges

The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops. It’s created using the range() function, where you can specify start, stop, and step values.

Ranges are immutable sequences, meaning their values cannot be altered. They are memory efficient because they don’t store every value in memory but generate them as needed.

4.7.1 - Creating Ranges

range objects are created using the range() function, which can take one, two, or three arguments:

# A range from 0 up to (but not including) 5
range_5 = range(5)

# A range from 1 to 5
range_1_to_5 = range(1, 6)

# A range from 0 to 10 with steps of 2
range_0_to_10_step_2 = range(0, 11, 2)

4.7.2 - Accessing Range Elements

Elements in a range can be accessed by their index, similar to lists and tuples:

# Accessing the first element
first_element = range_5[0]

# Accessing the last element
last_element = range_5[-1]

4.7.3 - Iterating Over Ranges

Ranges are commonly used for looping a specific number of times in for loops:

for i in range(5):
print(i)

4.7.4 - Range Immutability

Like tuples, ranges are immutable. Once a range is created, it cannot be altered:

# range_5[0] = 10  # This would raise a TypeError

4.7.5 - Length of a Range

The length of a range can be determined using the len() function:

length = len(range_5)  # 5

4.7.6 - Checking Membership in a Range

To check if a number is part of a range, use the in keyword:

if 3 in range_5:
print("3 is in the range")

4.7.7 - Slicing Ranges

Ranges support slicing, which creates a new range from a subset of the original:

# Getting the first three elements
first_three = range_5[:3]

# Slicing with a step
every_other = range_10[::2]

4.7.8 - Converting Ranges to Lists

Ranges can be converted to lists if you need an actual list of numbers:

range_list = list(range_5)

4.7.9 - Performance Characteristics

Ranges are memory-efficient because they only store the start, stop, and step values, not every individual number in the sequence.


4.7.10 - Reversing Ranges

Ranges can be reversed using slicing:

reversed_range = range_5[::-1]

4.7.11 - Summary Table of Range Operations and Characteristics

Operation/CharacteristicDescriptionExample
Creating RangesDefine a range using range().r = range(5)
Accessing ElementsAccess elements by their index.element = r[0]
Iterating Over RangesIterate over elements in a range.for x in r: print(x)
Range ImmutabilityRanges cannot be modified after creation.
Length of a RangeGet the number of elements in a range.len(r)
Checking MembershipCheck if a number is in the range.if 3 in r: ...
Slicing RangesCreate a new range from a subset.subset = r[:3]
Converting to ListsConvert ranges to lists.list(r)
PerformanceRanges are memory-efficient.
Reversing RangesReverse the range using slicing.reversed_r = r[::-1]