[prog] list membership in Python and Perl

Mary mary-linuxchix at puzzling.org
Wed May 11 07:29:30 EST 2005


On Tue, May 10, 2005, Caroline Johnston wrote:
> I think if you're looking up values in an array a lot, then generally
> its quicker and simpler to use a hash instead.

Yeah. Python's 'in' operator, along with most tests for membership of
lists, has a worst case time that grows linearly with the length of the
list. For data sets of unknown or large size in Python, I use
dictionaries.

As of Python 2.3 I think, you can do 'in' on dictionaries, which checks
the keys:

>>> 3 in {1 : 3, 4 : 7}
False
>>> 3 in {3 : 1, 4 : 7}
True

Before 2.3 you did dictionary.has_key() (which still works, but doesn't
have a list analogy).

-Mary


More information about the Programming mailing list