Junior
Is the Range object an iterator?
sobes.tech AI
Answer from AI
No. range is iterable, but not an iterator.
- Iterable object - an object that can return an iterator. It has the
__iter__()method. - Iterator - an object that supports the iterator protocol. It has the
__next__()method and the__iter__()method, which returns itself.
The range object generates values on demand but does not store them in memory, making it efficient for large sequences.
# Example of using range
my_range = range(5)
# my_range is iterable
print(hasattr(my_range, '__iter__')) # Output: True
# It can return an iterator
my_iterator = iter(my_range)
print(hasattr(my_iterator, '__next__')) # Output: True