It depends on what you are trying to do. If speed doesn't matter then use a in lst. If that matters, it will depend on whether you can first convert your list to another data structure (i.e. you will often look for items in a list of words), size, etc.
To give an idea:
import timeit a = range(10000) da = dict(zip(a, [None for i in a])) def list_first(): return 0 in a def dict_first(): return 0 in da def list_last(): return 9999 in a def dict_last(): return 9999 in da if __name__ == "__main__": for f in ["list_first", "dict_first", "list_last", "dict_last"]: t = timeit.Timer("%s()" % f, setup="from __main__ import %s" % f) print min(t.repeat(number=10000))
This gives me:
0.00302004814148 0.00318598747253 4.21943712234 0.004145860672
If you are looking for the element that is at the top of the list, using dict does not speed up as expected. If you are looking for an element at the end, then the difference is very significant (3 orders), although, as expected: dict uses a hash table, lists should look for each element one by one.
If the elements are comparable, you can also get significant speed by sorting your sequence and using binary search (log (N) instead of N, log (N) compares O (1) relatively quickly for N not too big in practice for python), or with using more advanced structures (binary search tree, etc.). This can become quite complex - data structures for quick searches are one of the most explored issues in CS.
David Cournapeau
source share