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":
[text snipped]
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.
The statement
my_object in my_list
does under the hood a for-loop and sequentially compares every object in my_list with my_object, so, potentially it does len(my_list) comparisons (it's O(n) in computerese speak). With a dictionary, that is
my_object in my_dict
it is O(1), that is, it is (asymptotically) constant and independent of the number of items in the dictionary.
So if you are going to do a lot of in tests, it does pay to put your objects in a dictionary.
With my best regards, G. Rodrigues _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor