Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?

前端 未结 11 1526
梦毁少年i
梦毁少年i 2020-11-22 03:46

It is my understanding that the range() function, which is actually an object type in Python 3, generates its contents on the fly, similar to a generator.

11条回答
  •  野性不改
    2020-11-22 04:25

    It's all about a lazy approach to the evaluation and some extra optimization of range. Values in ranges don't need to be computed until real use, or even further due to extra optimization.

    By the way, your integer is not such big, consider sys.maxsize

    sys.maxsize in range(sys.maxsize) is pretty fast

    due to optimization - it's easy to compare given integer just with min and max of range.

    but:

    Decimal(sys.maxsize) in range(sys.maxsize) is pretty slow.

    (in this case, there is no optimization in range, so if python receives unexpected Decimal, python will compare all numbers)

    You should be aware of an implementation detail but should not be relied upon, because this may change in the future.

提交回复
热议问题