Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

"Danny Yoo"'s response to "Ian!" on "[Tutor] is vs. == "

By: a guest on Jan 3rd, 2013  |  syntax: None  |  size: 1.64 KB  |  views: 5  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. On Thu, 18 Apr 2002, Ian! wrote:
  2.  
  3. > What's the difference between "is" and "=="? I always assumed they were
  4. > the same.
  5. >
  6. > >>> __name__ == '__main__'
  7. > 1
  8. > >>> __name__ is '__main__'
  9. > 0
  10.  
  11. Slightly different.
  12.  
  13.  
  14. '==' can be thought of as "value equality", that is, if two things look
  15. the same, == should return a true value.  (For those with a Java
  16. background, Python's == is actually doing something akin to an equals()
  17. method.)
  18.  
  19.  
  20. 'is' can be thought of as 'object identity', that is, if the two things
  21. actually are the same object.
  22.  
  23.  
  24. The concept is a little subtle, so let's use an example:
  25.  
  26. ###
  27. >>> my_name = "danny"
  28. >>> your_name = "ian"
  29. >>> my_name == your_name
  30. 0
  31. ###
  32.  
  33.  
  34. My name and your name are different.  But what about this?
  35.  
  36. ###
  37. >>> my_name[1:3] == your_name[1:3]
  38. 1
  39. ###
  40.  
  41. Our names share something in common.  *grin* We'd say that my_name[1:3]
  42. looks the same as your_name[1:3], so they're "equal" in some sense that's
  43. captured by the idea of '=='.  However, the sources of those strings are
  44. different, and we can see this when we check against object identity:
  45.  
  46. ###
  47. >>> my_name[1:3] is your_name[1:3]
  48. 0
  49. ###
  50.  
  51. 'is' allows us to make the distinction if the system is keeping track of
  52. two things that just look alike, or are actually the same thing.  Why this
  53. is useful isn't too obvious for strings; it's more of an issue when one is
  54. dealing with classes or mutable data structures like lists.
  55.  
  56. For now, you probably want to use '==' when you want to compare two things
  57. for equality.  When you learn about data structures, then 'is' will seem
  58. more relevant.
  59.  
  60.  
  61. Please feel free to ask more questions!  Good luck.