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

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

    Try x-1 in (i for i in range(x)) for large x values, which uses a generator comprehension to avoid invoking the range.__contains__ optimisation.

提交回复
热议问题