Re: Speed in Python

Guido.van.Rossum@cwi.nl
Sun, 14 Aug 1994 11:22:12 +0200

> What's the fastest way to check if a word is in a given set of words ?
> Should I do:
>
> list = ['word1', 'word2', 'word3']
> if i in list:
> ...
>
> or
>
> list = {'word1': None, 'word2': None, 'word3': None}
> if list.has_key(i):
> ...
>
> ?
>
> Of course, the word list is greater than 3 words.

That one's easy to answer: the latter! The former would do a linear
search in the list, while the latter uses hashing to quickly find an
item in a dictionary of any size.

In other words: lists are optimized for access by index, dictionaries
for access by key value...

Cheers (and glad for asking an easy yet new question :-)

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
<URL:http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>