Python – Why does python have to generate the full scope to test if it floats in scope?

Why does python have to generate the full scope to test if it floats in scope?… here is a solution to the problem.

Why does python have to generate the full scope to test if it floats in scope?

It’s really fast :

1 in range(100000000000000)

It’s really slow :

1.5 in range(100000000000000)

Why does the full range have to be generated to know that 1.5 is not in range(X) and step has to be an integer?

Solution

If we check source code :

Include function:

range_contains(rangeobject *r, PyObject *ob)
{
    if (PyLong_CheckExact(ob) || PyBool_Check(ob))
        return range_contains_long(r, ob);

return (int)_PySequence_IterSearch((PyObject*)r, ob,
                                   PY_ITERSEARCH_CONTAINS);
}

It seems to be checking if the integer or bool value method will be used for checking, and if not, then use PY_ITERSEARCH_CONTAINS.

Related Problems and Solutions