[Tutor] simple list query

Patrick Hall pathall at gmail.com
Sun Jan 2 18:34:00 CET 2005


Hi Dave,

> I have a list consisting of about 250 items, I need to know if a
> particular item is in the list. I know this is better suited to  a
> dictionary but thats not the way it ended up ;-)

> I could do a for loop to scan the list & compare each one, but I have a
> suspission that there is a better way ?

Indeed there is: just use the built-in "in":

>>> li = ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c']
>>> 'a' in li
True
>>> 'z' in li
False

That's a small example, but it will work equally well with a long
list. For instance, we can check to see if the words "Ahab", "whale",
and "pizza" are in the text of "Moby Dick" (I have the text in a file
called "moby.txt".)

>>> moby = open('moby.txt').read() # Moby Dick, the whole thing!
>>> mobywords = moby.split() # now mobywords has all the words in the text
>>> 'Ahab' in mobywords
True
>>> 'whale' in mobywords
True
>>> 'pizza' in mobywords
False

These results are unsurprising. 8^)

A list of 250 words is no problem -- "Moby Dick" has a couple hundred thousand:

>>> len(mobywords)
214112

I'm not sure I understand why you think a dictionary would be better
in this case, a list seems fine to me.

Best,
Pat


More information about the Tutor mailing list