not and is not problem

Stephen Hansen apt.shansen at gmail.com
Mon Jan 18 10:56:47 EST 2010


On Mon, Jan 18, 2010 at 7:43 AM, superpollo <utente at esempio.net> wrote:

> #!/usr/bin/env python
> data = "seq=123"
> name , value = data.split("=")
> print name
> print value
> if not name == "seq":
>    print "DOES NOT PRINT OF COURSE..."
> if name is not "seq":
>    print "WTF! WHY DOES IT PRINT?"
>

Because name really is not "seq"; "seq" is an entirely new and different
string. The "is" operator tests for object identity, == tests for equality.
"name is name" will always return True, everything else will always return
False.

For example, you can do:
    other = name
    if name is other:
        print "OK"

And it'll work, because those are the exact same object.

You only use 'is' and 'is not' when you really want to ask, 'Is this the
precisely same object?' Generally, that's only when you're testing if
something is or is not None. Sometimes is or is not True/False, but usually
'if x' is preferred.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100118/93d694ce/attachment-0001.html>


More information about the Python-list mailing list