[Tutor] searching for a value in an array

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 5 Sep 2002 12:10:41 -0700 (PDT)


On Thu, 5 Sep 2002, anthony polis wrote:

> How do you search for a value in an array? For example:
>
> I need to check to see if the string "bob" is in the array "people".


I think you'll like this one: it's basically what you just said:

###
>>> print 'bob' in ['jane', 'hector', 'alissa', 'john', 'lisa', 'bob',
...                 'iris']
1
###

The 'in' operator returns true if it can find our item in a list, and
false otherwise.  What Python does here is a "linear" scan:  it'll march
through our list until it either runs out of list, or if it finds 'bob'.


There are faster ways of seeing if someone is present in a group of
people: we can use a dictionary:

###
>>> people = { 'jane' : 1, 'hector' : 1, 'alissa' : 1 }
>>> 'jane' in people
1
>>> 'bob' in people
0
###



Hope this helps!