fast list search?

has has.temp2 at virgin.net
Wed Jun 9 13:59:11 EDT 2004


"Thomas Guettler" <guettli at thomas-guettler.de> wrote in message news:<pan.2004.06.09.10.22.54.20397 at thomas-guettler.de>...

> Use a dictionary instead of the list:
> 
> if not long_dict.has_key(new_int):
>     long_dict[new_int]=1

Or use an ordered list, which can be searched using an O(log n) binary
search algorithm (e.g. see the bisect module) instead of O(n) linear
search. Not sure which would be more efficient; if performance matters
you'd need to implement both and run comparative timing tests,
otherwise just use the dict solution as it's the simplest.

If your original list is unsorted and order is important, you can
maintain a second ordered list or dict alongside it purely for
performing your itemExists(i) tests. Remember to always add and remove
items to both to keep them in sync. And you can wrap the lot up as a
single custom BigUniqueList class to keep it neat and tidy and mediate
all access via accessor/mutator methods to ensure integrity is
maintained.



More information about the Python-list mailing list