Reputation: 257
Let's say there is a list a that contains both numbers and letters. Is there quick way to find out that the list doesn't contain some specific element. I plan to use it in conditions.
Upvotes: 15
Views: 44576
Reputation: 5404
do you mean
bool([x for x in alist if isinstance(x, int)])
better version (by Sven Marnach):
any(isinstance(x, int) for x in alist)
?
Upvotes: 0
Reputation: 80710
It depends on what you are trying to do. If speed does not matter, then use a in lst. If it does matter, it will depend on whether you can afford converting your list to a different data structure first (i.e. will you often look for items in the say list), 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 look for an item which is at the beginning of the list, using a dict does not speed things up, as expected. If you look for an item at the end, then the difference is very significant (3 order of magnitude), although as expected: dict use hashtable, lists needs to look for each item one after the other.
If items are comparable, you can also get a significant speed up by sorting your sequence and using a binary search (log(N) instead of N, log(N) being relatively fast compared O(1) for N not too big in practice for python), or using more advanced structures (binary search tree, etc...). It can get pretty complex - data structures for fast search is one of the most studied problem in CS after all.
Upvotes: 2
Reputation: 94172
Note: If you can put the elements as keys of a dict then testing for membership is much quicker thanks to the hashing algorithm. Will only be an issue if your list is very long or your app does a lot of this kind of thing. Otherwise, "X not in Y" as Sven says.
Upvotes: 3