is there a better way to check an array?

Steve M sjmaster at gmail.com
Thu Sep 1 13:22:56 EDT 2005


You can check for membership in a list at least these ways:

my_list.index(candidate)
-returns the index into my_list of the first occurrence of candidate.
Raises ValueError if candidate doesn't occur in my_list.

my_list.find(candidate)
-returns the index into my_list of the first occurrence of candidate.
Returns -1 if candidate doesn't occur in my_list.

candidate in my_list
-returns True if candidate occurs in my_list


The last is nicest (most pythonic?) if you don't actually need the
index, which it seems you don't. That being said, you should consider
the, what I believe is called, Complexity of your algorithm. In
particular, you should recall that checking for membership in a list
takes an amount of time proportional to the length of the list, while
checking for membership in a set (or dictionary) takes a constant
amount of time regardless of the size of the set. From what I see, it
appears that you don't necessarily need to keep the notRequiredAry
things in order, but that you really just need to kknow the set of
things that are not required. If you are making this check a lot, for
instance looping over a big list and checking for each member whether
it is not required, you should consider using a set instead of a list.
It might have the benefit of making your code more readable too.




More information about the Python-list mailing list