Difference between 'is' and '=='

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • mwql

    #1

    Difference between 'is' and '=='

    Hey guys, this maybe a stupid question, but I can't seem to find the
    result anywhere online. When is the right time to use 'is' and when
    should we use '=='?

    Thanks alot~

  • Rene Pijlman

    #2
    Re: Difference between 'is' and '=='

    mwql:[color=blue]
    >Hey guys, this maybe a stupid question, but I can't seem to find the
    >result anywhere online. When is the right time to use 'is' and when
    >should we use '=='?[/color]



    --
    René Pijlman

    Comment

    • Max M

      #3
      Re: Difference between 'is' and '=='

      mwql wrote:
      [color=blue]
      > Hey guys, this maybe a stupid question, but I can't seem to find the
      > result anywhere online. When is the right time to use 'is' and when
      > should we use '=='?[/color]

      "is" is like id(obj1) == id(obj2)
      [color=blue][color=green][color=darkred]
      >>> 100+1 == 101[/color][/color][/color]
      True
      [color=blue][color=green][color=darkred]
      >>> 100+1 is 101[/color][/color][/color]
      False

      They don't have the same id. (Think of id as memory adresses.)

      --

      hilsen/regards Max M, Denmark

      A small collection of CLAP synths and effects inspired by classic hardware.

      IT's Mad Science

      Phone: +45 66 11 84 94
      Mobile: +45 29 93 42 96

      Comment

      • Fuzzyman

        #4
        Re: Difference between 'is' and '=='


        mwql wrote:[color=blue]
        > Hey guys, this maybe a stupid question, but I can't seem to find the
        > result anywhere online. When is the right time to use 'is' and when
        > should we use '=='?
        >
        > Thanks alot~[/color]

        '==' is the equality operator. It is used to test if two objects are
        'equal'.

        'is' is the identity operator, it is used to test if two
        names/references point to the same object.

        a = {'a': 3}
        b = {'a': 3}
        a == b
        True
        a is b
        False
        c = a
        a is c
        True

        The two dictionaries a and b are equal, but are separate objects.
        (Under the hood, Python uses 'id' to determine identity).

        When you bind another name 'c' to point to dictionary a, they *are* the
        same object - so a *is* c.

        One place the 'is' operator is commonly used is when testing for None.
        You only ever have one instance of 'None', so

        a is None

        is quicker than

        a == None

        (It only needs to check identity not value.)

        I hope that helps.

        Fuzzyman
        http://www.voidspace.org.uk/python/index.shtml

        Comment

        • Joel Hedlund

          #5
          Re: Difference between 'is' and '=='

          > "is" is like id(obj1) == id(obj2)
          <snip>[color=blue]
          > (Think of id as memory adresses.)[/color]

          Which means that "is" comparisons in general will be faster than ==
          comparisons. According to PEP8 (python programming style guidelines) you should
          use 'is' when comparing to singletons like None. I take this to also include
          constants and such. That allows us to take short cuts through known terrain,
          such as in the massive_computa tions function below:

          --------------------------------------------------------------
          import time

          class LotsOfData(obje ct):
          def __init__(self, *data):
          self.data = data
          def __eq__(self, o):
          time.sleep(2) # time consuming computations...
          return self.data == o.data

          KNOWN_DATA = LotsOfData(1,2)
          same_data = KNOWN_DATA
          equal_data = LotsOfData(1,2)
          other_data = LotsOfData(2,3)

          def massive_computa tions(data = KNOWN_DATA):
          if data is KNOWN_DATA:
          return "very quick answer"
          elif data == KNOWN_DATA:
          return "quick answer"
          else:
          time.sleep(10) # time consuming computations...
          return "slow answer"

          print "Here we go!"
          print massive_computa tions()
          print massive_computa tions(same_data )
          print massive_computa tions(equal_dat a)
          print massive_computa tions(other_dat a)
          print "Done."
          --------------------------------------------------------------

          Cheers,
          Joel

          Comment

          • Roy Smith

            #6
            Re: Difference between 'is' and '=='

            In article <e08mr1$7lu$1@n ews.lysator.liu .se>,
            Joel Hedlund <joel.hedlund@g mail.com> wrote:
            [color=blue]
            > Which means that "is" comparisons in general will be faster than ==
            > comparisons.[/color]

            I thought that == automatically compared identify before trying to compare
            the values. Or am I thinking of some special case, like strings?

            Comment

            • Peter Hansen

              #7
              Re: Difference between 'is' and '=='

              Roy Smith wrote:[color=blue]
              > In article <e08mr1$7lu$1@n ews.lysator.liu .se>,
              > Joel Hedlund <joel.hedlund@g mail.com> wrote:[color=green]
              >>Which means that "is" comparisons in general will be faster than ==
              >>comparisons .[/color]
              >
              > I thought that == automatically compared identify before trying to compare
              > the values. Or am I thinking of some special case, like strings?[/color]

              You must be thinking of a special case:
              [color=blue][color=green][color=darkred]
              >>> class A:[/color][/color][/color]
              .... def __cmp__(self, other): return 1
              ....[color=blue][color=green][color=darkred]
              >>> a = A()
              >>> a is a[/color][/color][/color]
              True[color=blue][color=green][color=darkred]
              >>> a == a[/color][/color][/color]
              False


              -Peter

              Comment

              • Clemens Hepper

                #8
                Re: Difference between 'is' and '=='

                Roy Smith wrote:[color=blue]
                > In article <e08mr1$7lu$1@n ews.lysator.liu .se>,
                > Joel Hedlund <joel.hedlund@g mail.com> wrote:
                >[color=green]
                >> Which means that "is" comparisons in general will be faster than ==
                >> comparisons.[/color]
                >
                > I thought that == automatically compared identify before trying to compare
                > the values. Or am I thinking of some special case, like strings?[/color]

                Even for strings there is a performance difference:
                [color=blue][color=green][color=darkred]
                >>> timeit.Timer("' a'=='a'").timei t()[/color][/color][/color]
                0.2685978412628 1738[color=blue][color=green][color=darkred]
                >>> timeit.Timer("' a' is 'a'").timeit()[/color][/color][/color]
                0.2173049449920 6543

                mfg
                - eth

                Comment

                • Dan Sommers

                  #9
                  Re: Difference between 'is' and '=='

                  On Mon, 27 Mar 2006 14:52:46 +0200,
                  Joel Hedlund <joel.hedlund@g mail.com> wrote:
                  [color=blue]
                  > ... According to PEP8 (python programming style guidelines) you should
                  > use 'is' when comparing to singletons like None. I take this to also
                  > include constants and such ...[/color]

                  This does *not* also mean constants and such:

                  Python 2.4.2 (#1, Feb 22 2006, 08:02:53)
                  [GCC 4.0.1 (Apple Computer, Inc. build 5247)] on darwin
                  Type "help", "copyright" , "credits" or "license" for more information.[color=blue][color=green][color=darkred]
                  >>> a = 123456789
                  >>> a == 123456789[/color][/color][/color]
                  True[color=blue][color=green][color=darkred]
                  >>> a is 123456789[/color][/color][/color]
                  False[color=blue][color=green][color=darkred]
                  >>>[/color][/color][/color]

                  Regards,
                  Dan

                  --
                  Dan Sommers
                  <http://www.tombstoneze ro.net/dan/>
                  "I wish people would die in alphabetical order." -- My wife, the genealogist

                  Comment

                  • mwql

                    #10
                    Re: Difference between 'is' and '=='

                    It's really strange,

                    if
                    a = 1
                    b = 1
                    a is b ==> True

                    the same thing applies for strings, but not for dict, lists or tuples
                    I think the 'is' operator is useful for objects only, not for primitive
                    types,
                    I think I solved the mystery behind my bugged code =)

                    Comment

                    • Benji York

                      #11
                      Re: Difference between 'is' and '=='

                      mwql wrote:[color=blue]
                      > It's really strange,
                      >
                      > if
                      > a = 1
                      > b = 1
                      > a is b ==> True
                      >
                      > the same thing applies for strings[/color]

                      Not quite:
                      [color=blue][color=green][color=darkred]
                      >>> 'abc' is 'abc'[/color][/color][/color]
                      True[color=blue][color=green][color=darkred]
                      >>> 'abc' is 'ab' + 'c'[/color][/color][/color]
                      False

                      --
                      Benji York

                      Comment

                      • Clemens Hepper

                        #12
                        Re: Difference between 'is' and '=='

                        Dan Sommers wrote:[color=blue]
                        > This does *not* also mean constants and such:
                        >
                        > Python 2.4.2 (#1, Feb 22 2006, 08:02:53)
                        > [GCC 4.0.1 (Apple Computer, Inc. build 5247)] on darwin
                        > Type "help", "copyright" , "credits" or "license" for more information.[color=green][color=darkred]
                        > >>> a = 123456789
                        > >>> a == 123456789[/color][/color]
                        > True[color=green][color=darkred]
                        > >>> a is 123456789[/color][/color]
                        > False[/color]

                        It's strange: python seem to cache constants from 0 to 99:

                        for x in xrange(1000):
                        if not eval("%d"%x) is eval("%d"%x):
                        print x

                        for me it printed 100-999.

                        - eth

                        Comment

                        • Diez B. Roggisch

                          #13
                          Re: Difference between 'is' and '=='

                          mwql wrote:
                          [color=blue]
                          > It's really strange,
                          >
                          > if
                          > a = 1
                          > b = 1
                          > a is b ==> True
                          >
                          > the same thing applies for strings, but not for dict, lists or tuples
                          > I think the 'is' operator is useful for objects only, not for primitive
                          > types,
                          > I think I solved the mystery behind my bugged code =)[/color]

                          The reason that "is" works for small numbers is that these are cached for
                          performance reasons. Try
                          [color=blue][color=green][color=darkred]
                          >>> a = 1000000
                          >>> b = 1000000
                          >>> a is b[/color][/color][/color]
                          False

                          So - your conclusion is basically right: use is on (complex) objects, not on
                          numbers and strings and other built-ins. The exception from the rule is
                          None - that should only exist once, so

                          foo is not None

                          is considered better style than foo == None.

                          Diez

                          Comment

                          • Felipe Almeida Lessa

                            #14
                            Re: Difference between 'is' and '=='

                            Em Seg, 2006-03-27 às 08:23 -0500, Dan Sommers escreveu:[color=blue]
                            > On Mon, 27 Mar 2006 14:52:46 +0200,
                            > Joel Hedlund <joel.hedlund@g mail.com> wrote:
                            >[color=green]
                            > > ... According to PEP8 (python programming style guidelines) you should
                            > > use 'is' when comparing to singletons like None. I take this to also
                            > > include constants and such ...[/color]
                            >
                            > This does *not* also mean constants and such:
                            >
                            > Python 2.4.2 (#1, Feb 22 2006, 08:02:53)
                            > [GCC 4.0.1 (Apple Computer, Inc. build 5247)] on darwin
                            > Type "help", "copyright" , "credits" or "license" for more information.[color=green][color=darkred]
                            > >>> a = 123456789
                            > >>> a == 123456789[/color][/color]
                            > True[color=green][color=darkred]
                            > >>> a is 123456789[/color][/color]
                            > False[color=green][color=darkred]
                            > >>>[/color][/color][/color]

                            Not those kind of constants, but this one:

                            Python 2.4.2 (#2, Nov 20 2005, 17:04:48)
                            [GCC 4.0.3 20051111 (prerelease) (Debian 4.0.2-4)] on linux2
                            Type "help", "copyright" , "credits" or "license" for more information.[color=blue][color=green][color=darkred]
                            >>> CONST = 123456789
                            >>> a = CONST
                            >>> a == CONST[/color][/color][/color]
                            True[color=blue][color=green][color=darkred]
                            >>> a is CONST[/color][/color][/color]
                            True[color=blue][color=green][color=darkred]
                            >>>[/color][/color][/color]

                            --
                            Felipe.

                            Comment

                            • filipwasilewski@gmail.com

                              #15
                              Re: Difference between 'is' and '=='

                              Clemens Hepper wrote:[color=blue]
                              > It's strange: python seem to cache constants from 0 to 99:[/color]

                              That's true. The Python api doc says that Python keeps an array of
                              integer objects for all integers between -1 and 100. See
                              http://docs.python.org/api/intObjects.html.
                              This also seems to be true for integers from -5 to -2 on (ActiveState)
                              Python 2.4.2.

                              --
                              fw

                              Comment

                              Working...