I had heard that range was a generator, then later I realized that it is not via this helpful post. While this post thoroughly explains how the __contains__
method works in constant time, I was not able to find any source code reference on how the lazy sequence is created. I tried to decipher the source code myself but having only basic knowledge in C, I am struggling. I believe the code snippet below is how the __iter__
works in range (do correct me if I'm wrong) - could you shed some light on how the lazy sequence is implemented here? Is it any different from the lazy sequence of a generator?
range_iter(PyObject *seq)
{
rangeobject *r = (rangeobject *)seq;
longrangeiterobject *it;
long lstart, lstop, lstep;
PyObject *int_it;
long_range:
it = PyObject_New(longrangeiterobject, &PyLongRangeIter_Type);
if (it == NULL)
return NULL;
it->start = r->start;
it->step = r->step;
it->len = r->length;
it->index = _PyLong_Zero;
Py_INCREF(it->start);
Py_INCREF(it->step);
Py_INCREF(it->len);
Py_INCREF(it->index);
return (PyObject *)it;
}