好问题!是的,你提到的两种方法都必须遍历列表. Python不使用列表的哈希表,因为列表元素是不可限制的.
如果您知道约“Big O” notation,列表数据结构是通过查找已知索引(例如, my_list [13].会员考试是O(n).
还有其他数据结构针对成员身份测试(即__contains__)的O(1)速度进行了优化,即set和dict.这些都是用hashtables实现的.
以下是一个示例,说明如何使用IPython验证time-complexity的集合和列表,以确认这些声明:
In [1]: short_list, long_list = range(1000), range(10000)
In [2]: timeit 'potato' not in short_list
10000 loops, best of 3: 40.9 µs per loop
In [3]: timeit 'potato' not in long_list
1000 loops, best of 3: 440 µs per loop
In [4]: small_set, big_set = set(short_list), set(long_list)
In [5]: timeit 'potato' not in small_set
10000000 loops, best of 3: 72.9 ns per loop
In [6]: timeit 'potato' not in big_set
10000000 loops, best of 3: 84.5 ns per loop