Why does Python show the whole array?

Ben Finney ben+python at benfinney.id.au
Wed Apr 8 06:29:54 EDT 2009


Gilles Ganault <nospam at nospam.com> writes:

> I'd like to go through a list of e-mail addresses, and extract those
> that belong to well-known ISP's. For some reason I can't figure out,
> Python shows the whole list instead of just e-mails that match:
> 
> ======= script
> test = "toto at gmail.com"
> isp = ["gmail.com", "yahoo.com"]
> for item in isp:
> 	if test.find(item):
> 		print item
> ======= output
> gmail.com
> yahoo.com
> ======= 
> 
> Any idea why I'm also getting "yahoo.com"?

You've had answers on the “why” question.

Here's a suggestion for a better way that doesn't involve ‘find’:

    >>> known_domains = ["example.com", "example.org"]
    >>> test_address = "toto at example.com"
    >>> for domain in known_domains:
    ...     if test_address.endswith("@" + domain):
    ...         print domain
    ... 
    example.com
    >>> 

If all you want is a boolean “do any of these domains match the
address”, it's quicker and simpler to feed an iterator to ‘any’
(first introduced in Python 2.5), which short-cuts by exiting on the
first item that produces a True result:

    >>> known_domains = ["example.com", "example.org"]
    >>> test_address = "toto at example.com"
    >>> any(test_address.endswith("@" + domain) for domain in known_domains)
    True
    >>> test_address = "tinman at example.net"
    >>> any(test_address.endswith("@" + domain) for domain in known_domains)
    False

-- 
 \      “For my birthday I got a humidifier and a de-humidifier. I put |
  `\  them in the same room and let them fight it out.” —Steven Wright |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list