Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does python have to generate the full range to test if float in range?

This is really fast:

1 in range(100000000000000)

This is really slow:

1.5 in range(100000000000000)

Why does the full range have to be generated to know that 1.5 isn't in range(X) when step has to be an integer?

like image 368
SuperShoot Avatar asked Feb 14 '26 00:02

SuperShoot


1 Answers

If we check the source code:

The contains 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 appears to check if it will use an integer or boolean method to check, and if not it uses the PY_ITERSEARCH_CONTAINS.

like image 158
matt Avatar answered Feb 16 '26 12:02

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!