Another alternative: you can check if an item is in a list with if item in list:
, but this is order O(n). If you are dealing with big lists of items and all you need to know is whether something is a member of your list, you can convert the list to a set first and take advantage of constant time set lookup:
my_set = set(my_list)
if item in my_set: # much faster on average than using a list
# do something
Not going to be the correct solution in every case, but for some cases this might give you better performance.
Note that creating the set with set(my_list)
is also O(n), so if you only need to do this once then it isn't any faster to do it this way. If you need to repeatedly check membership though, then this will be O(1) for every lookup after that initial set creation.