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

前端 未结 11 1378
梦毁少年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:23

    1. Due to optimization, it is very easy to compare given integers just with min and max range.
    2. The reason that range() function is so fast in Python3 is that here we use mathematical reasoning for the bounds, rather than a direct iteration of the range object.
    3. So for explaining the logic here:
      • Check whether the number is between the start and stop.
      • Check whether the step precision value doesn't go over our number.
    4. Take an example, 997 is in range(4, 1000, 3) because:

      4 <= 997 < 1000, and (997 - 4) % 3 == 0.

提交回复
热议问题