I am wondering about the differences between range and generator in Python.
I have done some research and found some useful answers like this one and this one which explain the differences between these objects, despite the fact that they may return similar things.
One of the differences I wanted to explore is that the range object can be called multiple times while the generator object cannot. To demonstrate this more clearly, to myself, I considered the following code:
def my_range(first=0, last=3, step=1):
number = first
while number < last:
yield number
number+=step
a = range(0,3)
b = my_range()
for i in a:
print(i)
print("First")
for i in a:
print(i)
print("Second")
for i in b:
print(i)
print("Third")
for i in b:
print(i)
print("Fourth")
Which outputs:
0
1
2
First
0
1
2
Second
0
1
2
Third
Fourth
It is clear to me from this that the generator gets "used up" while range does not. But I am having trouble finding exactly where in the source code (as well as where the source code is itself) this sort of behavior is defined. I am not sure where to start to find and interpret the code that dictates that a range object can be used multiple times, but a generator object cannot.
I would like help with finding and understanding how property like how many times an object can be iterated over is implemented in Python's source code.