-
Notifications
You must be signed in to change notification settings - Fork 0
/
difference-between-and-is-in-python-and-when-to-use-each-of-them.html
229 lines (190 loc) · 15.7 KB
/
difference-between-and-is-in-python-and-when-to-use-each-of-them.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
<!DOCTYPE html>
<html lang="en">
<head>
<link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,400italic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="http://www.emadmokhtar.com/theme/stylesheet/style.min.css">
<link rel="stylesheet" type="text/css" href="http://www.emadmokhtar.com/theme/stylesheet/pygments.min.css">
<link rel="stylesheet" type="text/css" href="http://www.emadmokhtar.com/theme/stylesheet/font-awesome.min.css">
<link href="http://www.emadmokhtar.com/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="Emad Mokhtar's Framework Atom">
<link href="http://www.emadmokhtar.com/feeds/all.rss.xml" type="application/rss+xml" rel="alternate" title="Emad Mokhtar's Framework RSS">
<link rel="shortcut icon" href="http://www.emadmokhtar.com/images/favicon.ico" type="image/x-icon">
<link rel="icon" href="http://www.emadmokhtar.com/images/favicon.ico" type="image/x-icon">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="robots" content="" />
<meta name="author" content="Emad Mokhtar" />
<meta name="description" content="In Python there are many comparison operators; you always use them to check something in your code and let your code take decision according to the comparison In this article, I want to go deep with two operators == to check equality, and is to check identity." />
<meta name="keywords" content="python">
<meta property="og:site_name" content="Emad Mokhtar's Framework"/>
<meta property="og:title" content="Difference between `==` and `is` in Python, and when to use each of them"/>
<meta property="og:description" content="In Python there are many comparison operators; you always use them to check something in your code and let your code take decision according to the comparison In this article, I want to go deep with two operators == to check equality, and is to check identity."/>
<meta property="og:locale" content="en_US"/>
<meta property="og:url" content="http://www.emadmokhtar.com/difference-between-and-is-in-python-and-when-to-use-each-of-them.html"/>
<meta property="og:type" content="article"/>
<meta property="article:published_time" content="2019-01-26 17:00:00+03:00"/>
<meta property="article:modified_time" content=""/>
<meta property="article:author" content="http://www.emadmokhtar.com/author/emad-mokhtar.html">
<meta property="article:section" content="Python"/>
<meta property="article:tag" content="python"/>
<meta property="og:image" content="http://www.emadmokhtar.com/images/profile.jpg">
<title>Emad Mokhtar's Framework – Difference between `==` and `is` in Python, and when to use each of them</title>
</head>
<body>
<aside>
<div>
<a href="http://www.emadmokhtar.com">
<img src="http://www.emadmokhtar.com/images/profile.jpg" alt="" title="">
</a>
<h1><a href="http://www.emadmokhtar.com"></a></h1>
<p>Geek developer who's in search of code perfection.</p>
<nav>
<ul class="list">
<li><a href="http://www.emadmokhtar.com">Blog</a></li>
<li><a href="http://www.emadmokhtar.com/pages/podcasts.html#podcasts">Podcasts</a></li>
<li><a href="http://www.emadmokhtar.com/pages/projects.html#projects">Projects</a></li>
<li><a href="https://emadmokhtar.github.io/resume" target="_blank">Resume</a></li>
</ul>
</nav>
<ul class="social">
<li><a class="sc-envelope-o" href="mailto:emad@emadmokhtar.com" target="_blank"><i class="fa fa-envelope-o"></i></a></li>
<li><a class="sc-github" href="https://www.github.com/EmadMokhtar" target="_blank"><i class="fa fa-github"></i></a></li>
<li><a class="sc-linkedin" href="https://www.linkedin.com/in/emadmokhtar/" target="_blank"><i class="fa fa-linkedin"></i></a></li>
<li><a class="sc-stack-overflow" href="http://stackoverflow.com/users/373051/emad-mokhtar" target="_blank"><i class="fa fa-stack-overflow"></i></a></li>
<li><a class="sc-facebook" href="https://www.facebook.com/emadmokhtarframework/" target="_blank"><i class="fa fa-facebook"></i></a></li>
<li><a class="sc-twitter" href="https://twitter.com/emadmokhtar" target="_blank"><i class="fa fa-twitter"></i></a></li>
</ul>
</div>
</aside>
<main>
<nav>
<a href="http://www.emadmokhtar.com">Home</a>
<a href="https://emadmokhtar.github.io/resume">Resume</a>
<a href="http://www.emadmokhtar.com/feeds/all.atom.xml">Atom</a>
<a href="http://www.emadmokhtar.com/feeds/all.rss.xml">RSS</a>
</nav>
<article>
<header>
<h1 id="difference-between-and-is-in-python-and-when-to-use-each-of-them">Difference between `==` and `is` in Python, and when to use each of them</h1>
<p>Posted on Sat 26 January 2019 in <a href="http://www.emadmokhtar.com/category/python.html">Python</a> <b>Read in 3 min.</b></p>
</header>
<div>
<p><img alt="Difference" src="http://www.emadmokhtar.com/images/will-francis-1071726-unsplash.jpg"></p>
<p>In Python there are many <a href="https://realpython.com/python-operators-expressions/#comparison-operators">comparison operators</a>; you always use them to check something in your code and let your code take decision according to the comparison</p>
<p>In this article, I want to go deep with two operators <code>==</code> to check equality, and <code>is</code> to check identity.</p>
<h2>The <code>==</code> operator</h2>
<p>The equality comparison operator. </p>
<div class="highlight"><pre><span></span><span class="o">>>></span> <span class="mi">1</span> <span class="o">==</span> <span class="mi">1</span>
<span class="bp">True</span>
</pre></div>
<p>In the above code, we are checking whether the value of int <strong>1</strong> is an equal value of int <strong>1</strong>, in other words, we are checking the values equality here. </p>
<div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Number</span><span class="p">:</span>
<span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">number</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">number</span> <span class="o">=</span> <span class="n">number</span>
<span class="o">>>></span> <span class="n">Number</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="n">Number</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="bp">False</span> <span class="c1"># Wooot</span>
</pre></div>
<p>In the above code, we are checking if the values of 2 objects are equal. They are not equal. Classes in Python 🐍 have <a href="https://wiki.python.org/moin/DunderAlias">dunder methods</a> to implement special logic of magic.</p>
<iframe src="https://giphy.com/embed/12NUbkX6p4xOO4" width="480" height="440" frameBorder="0" class="giphy-embed" allowFullScreen></iframe>
<p><a href="https://giphy.com/gifs/shia-labeouf-12NUbkX6p4xOO4">via GIPHY</a></p>
<p>For example, <code>__init__()</code> is dunder method to initiate a new object or the class constructor. For our example above, there is a dunder method used to check the equality which is <code>__eq__()</code> , if we implement it correctly, the expression in the code about should work.</p>
<div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Number</span><span class="p">:</span>
<span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">number</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">number</span> <span class="o">=</span> <span class="n">number</span>
<span class="k">def</span> <span class="fm">__eq__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">another_number</span><span class="p">):</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">another_number</span><span class="p">,</span> <span class="n">Number</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">number</span> <span class="o">==</span> <span class="n">another_number</span><span class="o">.</span><span class="n">number</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">number</span> <span class="o">==</span> <span class="n">another_number</span>
<span class="o">>>></span> <span class="n">Number</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="n">Number</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="bp">True</span>
<span class="o">>>></span> <span class="n">Number</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span>
<span class="bp">True</span>
</pre></div>
<p>All right, now our class has a correct equality logic. The equality logic is implemented in <code>__eq__</code> method. It is also implemented in Python built-in types like Integers.</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">inspect</span>
<span class="kn">from</span> <span class="nn">pprint</span> <span class="kn">import</span> <span class="n">pprint</span>
<span class="c1"># 1 is object of int class</span>
<span class="n">pprint</span><span class="p">(</span><span class="n">inspect</span><span class="o">.</span><span class="n">getmembers</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
<span class="n">pprint</span><span class="p">(</span><span class="n">inspect</span><span class="o">.</span><span class="n">getmembers</span><span class="p">(</span><span class="nb">int</span><span class="p">))</span>
</pre></div>
<h2>The <code>is</code> operator</h2>
<p>The identity check operator</p>
<div class="highlight"><pre><span></span><span class="o">>>></span> <span class="n">none_obj</span> <span class="o">=</span> <span class="bp">None</span>
<span class="o">>>></span> <span class="n">none_obj</span> <span class="ow">is</span> <span class="bp">None</span>
<span class="bp">True</span>
<span class="o">>>></span> <span class="n">number_one</span> <span class="o">=</span> <span class="mi">1</span>
<span class="o">>>></span> <span class="n">number_one</span> <span class="ow">is</span> <span class="mi">1</span>
</pre></div>
<p>In Python, every object created will store a reference to it, like in the above code <strong>none_obj</strong> which is storing a reference to <strong>None</strong> , and <strong>number_one</strong> object is storing a reference to <strong>1</strong>. Let’s examine how this is done by Python.</p>
<div class="highlight"><pre><span></span><span class="o">>>></span> <span class="n">none_obj</span> <span class="o">=</span> <span class="bp">None</span>
<span class="o">>>></span> <span class="nb">id</span><span class="p">(</span><span class="n">none_obj</span><span class="p">)</span>
<span class="mi">4304631824</span>
<span class="o">>>></span> <span class="nb">id</span><span class="p">(</span><span class="bp">None</span><span class="p">)</span>
<span class="mi">4304631824</span>
<span class="o">>>></span> <span class="nb">id</span><span class="p">(</span><span class="n">number_one</span><span class="p">)</span>
<span class="mi">4304948352</span>
<span class="o">>>></span> <span class="nb">id</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="mi">4304948352</span>
</pre></div>
<p>When you create a new variable that stores an object or value, this variable name stores a reference to it, so if you create another variable to store the same object, Python stores a pointer to this object instead of creating a new one.</p>
<div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="n">Number</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">a</span>
<span class="o">>>></span> <span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">),</span> <span class="nb">id</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="p">(</span><span class="mi">4520963656</span><span class="p">,</span> <span class="mi">4520963656</span><span class="p">)</span>
<span class="o">>>></span> <span class="n">a</span> <span class="ow">is</span> <span class="n">b</span>
<span class="bp">True</span>
</pre></div>
<p>Technically speaking, when you check the identity, Python checks <code>id(a) == id(b)</code>, which means:
Do objects <strong>a</strong> and <strong>b</strong> refer to the same object? So the answer will be <strong>True</strong> if they refer to the same object.</p>
<h2>Conclusion</h2>
<p>If you need to check the value equality, use the <code>==</code> operator and if you need to check whether 2 objects are the same, use <code>is</code>.</p>
<p>Happy Pythoning 😉</p>
</div>
<div class="tag-cloud">
<p>
<a href="http://www.emadmokhtar.com/tag/python.html">python</a>
</p>
</div>
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'emadmokhtarsframework';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
</article>
<footer>
<p>© Emad Mokhtar </p>
<p>Built using <a href="http://getpelican.com" target="_blank">Pelican</a> - <a href="https://github.com/alexandrevicenzi/flex" target="_blank">Flex</a> theme by <a href="http://alexandrevicenzi.com" target="_blank">Alexandre Vicenzi</a></p> </footer>
</main>
<!-- Google Analytics -->
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-11401860-2', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "BlogPosting",
"name": "Difference between `==` and `is` in Python, and when to use each of them",
"headline": "Difference between `==` and `is` in Python, and when to use each of them",
"datePublished": "2019-01-26 17:00:00+03:00",
"dateModified": "",
"author": {
"@type": "Person",
"name": "Emad Mokhtar",
"url": "http://www.emadmokhtar.com/author/emad-mokhtar.html"
},
"image": "http://www.emadmokhtar.com/images/profile.jpg",
"url": "http://www.emadmokhtar.com/difference-between-and-is-in-python-and-when-to-use-each-of-them.html",
"description": "In Python there are many comparison operators; you always use them to check something in your code and let your code take decision according to the comparison In this article, I want to go deep with two operators == to check equality, and is to check identity."
}
</script></body>
</html>