[Tutor] Finding Match in nexted tuple

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Apr 22 13:16:34 EDT 2004

On Wed, 21 Apr 2004, Tim Johnson wrote:

> * Magnus Lycka <magnus at thinkware.se> [040421 17:04]:
> > Tim Johnson wrote:
> > > Let's say I have a list of zip codes returned from a MySQLdb query
> > > zip_code_list = (('84536',), ('85003',), ('85004',), ('85006',),
> > >                  ('85007',), ('85008',))
> > > # and I want to look for a match for a value like '85004'
> >
> > If you know that the format is exactly like that, you can
> > simply do:
> >
> > if ('85004',) in zip_code_list:
> >     print "Found!"
>   Good tip..
> > ..but maybe that's not what you intended? If '85004' might
> > just be in an arbitrary position in a sequence of tuples with
> > more columns than the zip codes, you could for instance do:
> >
> > if '85004' in str(zip_code_list):
> >     print "Found!"
>   Eureka! That's what I meant by a 'pythonesque' solution.

Hi Jim,

Be wary of string solutions.  In this particular case, a string-search
approach will work because we're assuming fixed-width, comma-delimited
zip-code data.  In the general case, we have to be careful, because the
'in' check on strings is a "substring' check.

Not only is something like:

    'hello' in 'hello world'

True, but

    'or' in 'hello world'

is also True.  That's why string-searching approaches to lookup can be
potentially flaky.

I suspect that the first approach that Magnus suggested,

    if ('85004',) in zip_code_list: ...

is probably faster than the str() approach, but I have no empirical data
yet to back my guesses.  *grin* But I'd feel more secure about using this,
as opposed to "if '85004' in str(zip_code_list): ...".

Both approaches, though, use a linear scan through 'zip_code_list'.  If
your list is long, and if you plan to do repeated searches, then you may
want to later look into 'sets':


as they allow us to look things up more efficiently than in the two
previous approaches.

Hope this helps!

More information about the Tutor mailing list