- Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathVariables_and_Assignment.html
349 lines (317 loc) · 33.8 KB
/
Variables_and_Assignment.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
<!DOCTYPE html>
<htmlclass="writer-html5" lang="en" >
<head>
<metacharset="utf-8" /><metacontent="Topic: variable naming and assignment, Difficulty: Medium, Category: Section" name="description" />
<metacontent="variable naming, valid names, mutable, immutable, reference, pointer" name="keywords" />
<metaname="viewport" content="width=device-width, initial-scale=1.0" />
<title>Variables & Assignment — Python Like You Mean It</title>
<linkrel="stylesheet" href="../_static/pygments.css" type="text/css" />
<linkrel="stylesheet" href="../_static/css/theme.css" type="text/css" />
<linkrel="stylesheet" href="../_static/my_theme.css" type="text/css" />
<!--[if lt IE 9]>
<script src="../_static/js/html5shiv.min.js"></script>
<![endif]-->
<scriptdata-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<scriptsrc="../_static/jquery.js"></script>
<scriptsrc="../_static/underscore.js"></script>
<scriptsrc="../_static/doctools.js"></script>
<scriptasync="async" src="https://www.googletagmanager.com/gtag/js?id=UA-115029372-1"></script>
<scriptsrc="../_static/gtag.js"></script>
<scriptcrossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script>window.MathJax={"tex": {"inlineMath": [["$","$"],["\\(","\\)"]],"processEscapes": true},"options": {"ignoreHtmlClass": "tex2jax_ignore|mathjax_ignore|document","processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script>
<scriptdefer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<scriptsrc="../_static/js/theme.js"></script>
<linkrel="index" title="Index" href="../genindex.html" />
<linkrel="search" title="Search" href="../search.html" />
<linkrel="next" title="Introducing Control Flow" href="Introduction.html" />
<linkrel="prev" title="Sequence Types" href="SequenceTypes.html" />
</head>
<bodyclass="wy-body-for-nav">
<divclass="wy-grid-for-nav">
<navdata-toggle="wy-nav-shift" class="wy-nav-side">
<divclass="wy-side-scroll">
<divclass="wy-side-nav-search" >
<ahref="../index.html" class="icon icon-home"> Python Like You Mean It
</a>
<divclass="version">
1.4
</div>
<divrole="search">
<formid="rtd-search-form" class="wy-form" action="../search.html" method="get">
<inputtype="text" name="q" placeholder="Search docs" />
<inputtype="hidden" name="check_keywords" value="yes" />
<inputtype="hidden" name="area" value="default" />
</form>
</div>
</div><divclass="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
<pclass="caption" role="heading"><spanclass="caption-text">Table of Contents:</span></p>
<ulclass="current">
<liclass="toctree-l1"><aclass="reference internal" href="../intro.html">Python Like You Mean It</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../module_1.html">Module 1: Getting Started with Python</a></li>
<liclass="toctree-l1 current"><aclass="reference internal" href="../module_2.html">Module 2: The Essentials of Python</a><ulclass="current">
<liclass="toctree-l2"><aclass="reference internal" href="Basic_Objects.html">Basic Object Types</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="SequenceTypes.html">Sequence Types</a></li>
<liclass="toctree-l2 current"><aclass="current reference internal" href="#">Variables & Assignment</a><ul>
<liclass="toctree-l3"><aclass="reference internal" href="#Valid-Names-for-Variables">Valid Names for Variables</a></li>
<liclass="toctree-l3"><aclass="reference internal" href="#Mutable-and-Immutable-Objects">Mutable and Immutable Objects</a><ul>
<liclass="toctree-l4"><aclass="reference internal" href="#Mutable-&-Immutable-Types-of-Objects">Mutable & Immutable Types of Objects</a></li>
</ul>
</li>
<liclass="toctree-l3"><aclass="reference internal" href="#Referencing-a-Mutable-Object-with-Multiple-Variables">Referencing a Mutable Object with Multiple Variables</a></li>
<liclass="toctree-l3"><aclass="reference internal" href="#Reading-Comprehension-Exercise-Solutions:">Reading Comprehension Exercise Solutions:</a></li>
</ul>
</li>
<liclass="toctree-l2"><aclass="reference internal" href="Introduction.html">Introducing Control Flow</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="ConditionalStatements.html">Conditional Statements</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="ForLoops.html">For-Loops and While-Loops</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="Iterables.html">Iterables</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="Generators_and_Comprehensions.html">Generators & Comprehension Expressions</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="Itertools.html">Python’s “Itertools”</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="Functions.html">Basics of Functions</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="Scope.html">Scope</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="DataStructures.html">Data Structures (Part I): Introduction</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="DataStructures_II_Dictionaries.html">Data Structures (Part II): Dictionaries</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="DataStructures_III_Sets_and_More.html">Data Structures (Part III): Sets & the Collections Module</a></li>
</ul>
</li>
<liclass="toctree-l1"><aclass="reference internal" href="../module_2_problems.html">Module 2: Problems</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../module_3.html">Module 3: The Essentials of NumPy</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../module_3_problems.html">Module 3: Problems</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../module_4.html">Module 4: Object Oriented Programming</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../module_5.html">Module 5: Odds and Ends</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../changes.html">Changelog</a></li>
</ul>
</div>
</div>
</nav>
<sectiondata-toggle="wy-nav-shift" class="wy-nav-content-wrap"><navclass="wy-nav-top" aria-label="Mobile navigation menu" >
<idata-toggle="wy-nav-top" class="fa fa-bars"></i>
<ahref="../index.html">Python Like You Mean It</a>
</nav>
<divclass="wy-nav-content">
<divclass="rst-content">
<divrole="navigation" aria-label="Page navigation">
<ulclass="wy-breadcrumbs">
<li><ahref="../index.html" class="icon icon-home"></a> »</li>
<li><ahref="../module_2.html">Module 2: The Essentials of Python</a> »</li>
<li>Variables & Assignment</li>
<liclass="wy-breadcrumbs-aside">
<ahref="../_sources/Module2_EssentialsOfPython/Variables_and_Assignment.md.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<divrole="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<divitemprop="articleBody">
<style>
/* CSS overrides for sphinx_rtd_theme */
/* 24px margin */
.nbinput.nblast.container,
.nboutput.nblast.container {
margin-bottom:19px; /* padding has already 5px */
}
/* ... except between code cells! */
.nblast.container+ .nbinput.container {
margin-top:-19px;
}
.admonition>p:before {
margin-right:4px; /* make room for the exclamation icon */
}
/* Fix math alignment, see https://github.com/rtfd/sphinx_rtd_theme/pull/686 */
.math {
text-align: unset;
}
</style>
<divclass="section" id="Variables-&-Assignment">
<h1>Variables & Assignment<aclass="headerlink" href="#Variables-&-Assignment" title="Permalink to this headline"></a></h1>
<divclass="admonition warning">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Note</strong>:</p>
<p>There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page.</p>
</div>
<p>Variables permit us to write code that is flexible and amendable to repurpose. Suppose we want to write code that logs a student’s grade on an exam. The logic behind this process should not depend on whether we are logging Brian’s score of 92% versus Ashley’s score of 94%. As such, we can utilize variables, say <codeclass="docutils literal notranslate"><spanclass="pre">name</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">grade</span></code>, to serve as placeholders for this information. In this subsection, we will demonstrate how to define variables in Python.</p>
<p>In Python, the <codeclass="docutils literal notranslate"><spanclass="pre">=</span></code> symbol represents the “assignment” operator. The variable goes to the left of <codeclass="docutils literal notranslate"><spanclass="pre">=</span></code>, and the object that is being assigned to the variable goes to the right:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="n">name</span><spanclass="o">=</span><spanclass="s2">"Brian"</span><spanclass="c1"># the variable `name` is being assigned the string "Brian"</span>
<spanclass="n">grade</span><spanclass="o">=</span><spanclass="mi">92</span><spanclass="c1"># the variable `grade` is being assigned the integer 92</span>
</pre></div>
</div>
<p>Attempting to reverse the assignment order (e.g. <codeclass="docutils literal notranslate"><spanclass="pre">92</span><spanclass="pre">=</span><spanclass="pre">name</span></code>) will result in a syntax error. When a variable is assigned an object (like a number or a string), it is common to say that the variable <strong>is a reference to</strong> that object. For example, the variable <codeclass="docutils literal notranslate"><spanclass="pre">name</span></code> references the string <codeclass="docutils literal notranslate"><spanclass="pre">"Brian"</span></code>. This means that, once a variable is assigned an object, it can be used elsewhere in your code as a reference to (or placeholder for) that object:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># demonstrating the use of variables in code</span>
<spanclass="n">name</span><spanclass="o">=</span><spanclass="s2">"Brian"</span>
<spanclass="n">grade</span><spanclass="o">=</span><spanclass="mi">92</span>
<spanclass="n">failing</span><spanclass="o">=</span><spanclass="kc">False</span>
<spanclass="k">if</span><spanclass="n">grade</span><spanclass="o"><</span><spanclass="mi">60</span><spanclass="p">:</span>
<spanclass="n">failing</span><spanclass="o">=</span><spanclass="kc">True</span>
<spanclass="c1"># writes: name | grade | passing-status</span>
<spanclass="c1"># to the end of the file "student_grades.txt"</span>
<spanclass="k">with</span><spanclass="nb">open</span><spanclass="p">(</span><spanclass="s2">"student_grades.txt"</span><spanclass="p">,</span><spanclass="n">mode</span><spanclass="o">=</span><spanclass="s2">"a"</span><spanclass="p">)</span><spanclass="k">as</span><spanclass="n">opened_file</span><spanclass="p">:</span>
<spanclass="n">opened_file</span><spanclass="o">.</span><spanclass="n">write</span><spanclass="p">(</span><spanclass="s2">"</span><spanclass="si">{}</span><spanclass="s2"> | </span><spanclass="si">{}</span><spanclass="s2"> | </span><spanclass="si">{}</span><spanclass="s2">"</span><spanclass="o">.</span><spanclass="n">format</span><spanclass="p">(</span><spanclass="n">name</span><spanclass="p">,</span><spanclass="n">grade</span><spanclass="p">,</span><spanclass="n">failing</span><spanclass="p">))</span>
</pre></div>
</div>
<divclass="section" id="Valid-Names-for-Variables">
<h2>Valid Names for Variables<aclass="headerlink" href="#Valid-Names-for-Variables" title="Permalink to this headline"></a></h2>
<p>A variable name may consist of alphanumeric characters (<codeclass="docutils literal notranslate"><spanclass="pre">a-z</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">A-Z</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">0-9</span></code>) and the underscore symbol (<codeclass="docutils literal notranslate"><spanclass="pre">_</span></code>); a valid name cannot begin with a numerical value.</p>
<ulclass="simple">
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">var</span></code>: valid</p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">_var2</span></code>: valid</p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">ApplePie_Yum_Yum</span></code>: valid</p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">2cool</span></code>: <strong>invalid</strong> (begins with a numerical character)</p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">I.am.the.best</span></code>: <strong>invalid</strong> (contains <codeclass="docutils literal notranslate"><spanclass="pre">.</span></code>)</p></li>
</ul>
<p>They also cannot conflict with character sequences that are reserved by the Python language. As such, the following cannot be used as variable names:</p>
<ulclass="simple">
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">for</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">while</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">break</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">pass</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">continue</span></code></p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">in</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">is</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">not</span></code></p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">if</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">else</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">elif</span></code></p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">def</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">class</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">return</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">yield</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">raises</span></code></p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">import</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">from</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">as</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">with</span></code></p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">try</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">except</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">finally</span></code></p></li>
</ul>
<p>There are other unicode characters that are permitted as valid characters in a Python variable name, but it is not worthwhile to delve into those details here.</p>
</div>
<divclass="section" id="Mutable-and-Immutable-Objects">
<h2>Mutable and Immutable Objects<aclass="headerlink" href="#Mutable-and-Immutable-Objects" title="Permalink to this headline"></a></h2>
<p>The <strong>mutability</strong> of an object refers to its ability to have its state changed. A <strong>mutable object</strong> can have its state changed, whereas an <strong>immutable object</strong> cannot. For instance, a list is an example of a mutable object. Once formed, we are able to update the contents of a list - replacing, adding to, and removing its elements.</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># demonstrating the mutability of a list</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="o">=</span><spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="mi">3</span><spanclass="p">]</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="p">[</span><spanclass="mi">0</span><spanclass="p">]</span><spanclass="o">=</span><spanclass="o">-</span><spanclass="mi">4</span><spanclass="c1"># replace element-0 of `x` with -4</span>
<spanclass="o">>>></span><spanclass="n">x</span>
<spanclass="p">[</span><spanclass="o">-</span><spanclass="mi">4</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="mi">3</span><spanclass="p">]</span>
</pre></div>
</div>
<p>To spell out what is transpiring here, we:</p>
<olclass="arabic simple">
<li><p>Create (initialize) a list with the state <codeclass="docutils literal notranslate"><spanclass="pre">[1,</span><spanclass="pre">2,</span><spanclass="pre">3]</span></code>.</p></li>
<li><p>Assign this list to the variable <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code>; <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> is now a reference to that list.</p></li>
<li><p>Using our referencing variable, <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code>, update element-0 of the list to store the integer <codeclass="docutils literal notranslate"><spanclass="pre">-4</span></code>.</p></li>
</ol>
<p>This does not create a new list object, rather it <em>mutates</em> our original list. This is why printing <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> in the console displays <codeclass="docutils literal notranslate"><spanclass="pre">[-4,</span><spanclass="pre">2,</span><spanclass="pre">3]</span></code> and not <codeclass="docutils literal notranslate"><spanclass="pre">[1,</span><spanclass="pre">2,</span><spanclass="pre">3]</span></code>.</p>
<p>A tuple is an example of an immutable object. Once formed, there is no mechanism by which one can change of the state of a tuple; and any code that appears to be updating a tuple is in fact creating an entirely new tuple.</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># demonstrating to the immutability of a tuple</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="o">=</span><spanclass="p">(</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="mi">3</span><spanclass="p">)</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="p">[</span><spanclass="mi">0</span><spanclass="p">]</span><spanclass="o">=</span><spanclass="o">-</span><spanclass="mi">4</span><spanclass="c1"># attempt to replace element-0 of `x` with -4</span>
<spanclass="o">---------------------------------------------------------------------------</span>
<spanclass="ne">TypeError</span><spanclass="n">Traceback</span><spanclass="p">(</span><spanclass="n">most</span><spanclass="n">recent</span><spanclass="n">call</span><spanclass="n">last</span><spanclass="p">)</span>
<spanclass="o"><</span><spanclass="n">ipython</span><spanclass="o">-</span><spanclass="nb">input</span><spanclass="o">-</span><spanclass="mi">11</span><spanclass="o">-</span><spanclass="n">a858573fdc63</span><spanclass="o">></span><spanclass="ow">in</span><spanclass="o"><</span><spanclass="n">module</span><spanclass="o">></span><spanclass="p">()</span>
<spanclass="mi">1</span><spanclass="n">x</span><spanclass="o">=</span><spanclass="p">(</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="mi">3</span><spanclass="p">)</span>
<spanclass="o">----></span><spanclass="mi">2</span><spanclass="n">x</span><spanclass="p">[</span><spanclass="mi">0</span><spanclass="p">]</span><spanclass="o">=</span><spanclass="o">-</span><spanclass="mi">4</span><spanclass="c1"># attempt to replace element-0 of `x` with -4</span>
<spanclass="ne">TypeError</span><spanclass="p">:</span><spanclass="s1">'tuple'</span><spanclass="nb">object</span><spanclass="n">does</span><spanclass="ow">not</span><spanclass="n">support</span><spanclass="n">item</span><spanclass="n">assignment</span>
</pre></div>
</div>
<divclass="section" id="Mutable-&-Immutable-Types-of-Objects">
<h3>Mutable & Immutable Types of Objects<aclass="headerlink" href="#Mutable-&-Immutable-Types-of-Objects" title="Permalink to this headline"></a></h3>
<p>The following are some common immutable and mutable objects in Python. These will be important to have in mind as we start to work with dictionaries and sets.</p>
<p><strong>Some immutable objects</strong></p>
<ulclass="simple">
<li><p><aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Number-Types">numbers</a> (integers, floating-point numbers, complex numbers)</p></li>
<li><p><aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Strings">strings</a></p></li>
<li><p><aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#Tuples">tuples</a></p></li>
<li><p><aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#The-Boolean-Type">booleans</a></p></li>
<li><p><aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.html#The-%E2%80%9CSet%E2%80%9D-Data-Structure">“frozen”-sets</a></p></li>
</ul>
<p><strong>Some mutable objects</strong></p>
<ulclass="simple">
<li><p><aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Lists">lists</a></p></li>
<li><p><aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html">dictionaries</a></p></li>
<li><p><aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.html#The-%E2%80%9CSet%E2%80%9D-Data-Structure">sets</a></p></li>
<li><p><aclass="reference external" href="https://www.pythonlikeyoumeanit.com/module_3.html">NumPy arrays</a></p></li>
</ul>
</div>
</div>
<divclass="section" id="Referencing-a-Mutable-Object-with-Multiple-Variables">
<h2>Referencing a Mutable Object with Multiple Variables<aclass="headerlink" href="#Referencing-a-Mutable-Object-with-Multiple-Variables" title="Permalink to this headline"></a></h2>
<p>It is possible to assign variables to other, existing variables. Doing so will cause the variables to reference the same object:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># demonstrating the behavior of variables</span>
<spanclass="c1"># referencing the same object</span>
<spanclass="o">>>></span><spanclass="n">list1</span><spanclass="o">=</span><spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="mi">3</span><spanclass="p">]</span><spanclass="c1"># `list1` references [1, 2, 3]</span>
<spanclass="o">>>></span><spanclass="n">list2</span><spanclass="o">=</span><spanclass="n">list1</span><spanclass="c1"># `list2` and `list1` now both reference [1, 2, 3]</span>
<spanclass="o">>>></span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">list1</span><spanclass="p">)</span>
<spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="mi">3</span><spanclass="p">]</span>
<spanclass="o">>>></span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">list2</span><spanclass="p">)</span>
<spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="mi">3</span><spanclass="p">]</span>
</pre></div>
</div>
<p>What this entails is that these common variables will reference the <em>same instance</em> of the list. Meaning that if the list changes, all of the variables referencing that list will reflect this change:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="n">list1</span><spanclass="o">.</span><spanclass="n">append</span><spanclass="p">(</span><spanclass="mi">4</span><spanclass="p">)</span><spanclass="c1"># append 4 to the end of [1, 2, 3]</span>
<spanclass="gp">>>> </span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">list1</span><spanclass="p">)</span>
<spanclass="go">[1, 2, 3, 4]</span>
</pre></div>
</div>
<p>We can see that <codeclass="docutils literal notranslate"><spanclass="pre">list2</span></code> is still assigned to reference the <em>same, updated</em> list as <codeclass="docutils literal notranslate"><spanclass="pre">list1</span></code>:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">list2</span><spanclass="p">)</span>
<spanclass="go">[1, 2, 3, 4]</span>
</pre></div>
</div>
<p>In general, assigning a variable <codeclass="docutils literal notranslate"><spanclass="pre">b</span></code> to a variable <codeclass="docutils literal notranslate"><spanclass="pre">a</span></code> will cause the variables to reference the <em>same</em> object in the system’s memory, and assigning <codeclass="docutils literal notranslate"><spanclass="pre">c</span></code> to <codeclass="docutils literal notranslate"><spanclass="pre">a</span></code> or <codeclass="docutils literal notranslate"><spanclass="pre">b</span></code> will simply have a third variable reference this same object. Then any change (a.k.a <em>mutation</em>) of the object will be reflected in all of the variables that reference it (<codeclass="docutils literal notranslate"><spanclass="pre">a</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">b</span></code>, and <codeclass="docutils literal notranslate"><spanclass="pre">c</span></code>).</p>
<p>Of course, assigning two variables to identical but <em>distinct</em> lists means that a change to one list will not affect the other:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="n">list1</span><spanclass="o">=</span><spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="mi">3</span><spanclass="p">]</span><spanclass="c1"># `list1` references [1, 2, 3]</span>
<spanclass="gp">>>> </span><spanclass="n">list2</span><spanclass="o">=</span><spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="mi">3</span><spanclass="p">]</span><spanclass="c1"># `list2` references a *separate* list, whose value is [1, 2, 3]</span>
<spanclass="gp">>>> </span><spanclass="n">list1</span><spanclass="o">.</span><spanclass="n">append</span><spanclass="p">(</span><spanclass="mi">4</span><spanclass="p">)</span><spanclass="c1"># append 4 to the end of [1, 2, 3]</span>
<spanclass="gp">>>> </span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">list1</span><spanclass="p">)</span>
<spanclass="go">[1, 2, 3, 4]</span>
<spanclass="gp">>>> </span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">list2</span><spanclass="p">)</span><spanclass="c1"># `list2` still references its own list</span>
<spanclass="go">[1, 2, 3]</span>
</pre></div>
</div>
<divclass="admonition note">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Reading Comprehension: Does slicing a list produce a reference to that list?</strong></p>
<p>Suppose <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> is assigned a list, and that <codeclass="docutils literal notranslate"><spanclass="pre">y</span></code> is assigned a “slice” of <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code>. Do <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">y</span></code> reference the same list? That is, if you update part of the subsequence common to <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">y</span></code>, does that change show up in both of them? Write some simple code to investigate this.</p>
</div>
<divclass="admonition note">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Reading Comprehension: Understanding References</strong></p>
<p>Based on our discussion of mutable and immutable objects, predict what the value of <codeclass="docutils literal notranslate"><spanclass="pre">y</span></code> will be in the following circumstance:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="n">x</span><spanclass="o">=</span><spanclass="mi">3</span>
<spanclass="gp">>>> </span><spanclass="n">y</span><spanclass="o">=</span><spanclass="n">x</span>
<spanclass="go"># shorthand for: `x = x * 3`</span>
<spanclass="gp">>>> </span><spanclass="n">x</span><spanclass="o">*=</span><spanclass="mi">3</span>
<spanclass="gp">>>> </span><spanclass="n">x</span>
<spanclass="go">9</span>
<spanclass="gp">>>> </span><spanclass="n">y</span>
<spanclass="go">???</span>
</pre></div>
</div>
</div>
</div>
<divclass="section" id="Reading-Comprehension-Exercise-Solutions:">
<h2>Reading Comprehension Exercise Solutions:<aclass="headerlink" href="#Reading-Comprehension-Exercise-Solutions:" title="Permalink to this headline"></a></h2>
<p><strong>Does slicing a list produce a reference to that list?: Solution</strong></p>
<p>Based on the following behavior, we can conclude that slicing a list does <strong>not</strong> produce a reference to the original list. Rather, slicing a list produces a copy of the appropriate subsequence of the list:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="n">x</span><spanclass="o">=</span><spanclass="p">[</span><spanclass="mi">0</span><spanclass="p">,</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="mi">3</span><spanclass="p">]</span>
<spanclass="gp">>>> </span><spanclass="n">y</span><spanclass="o">=</span><spanclass="n">x</span><spanclass="p">[:</span><spanclass="mi">2</span><spanclass="p">]</span>
<spanclass="gp">>>> </span><spanclass="n">y</span><spanclass="c1"># does `y` reference the same list as `x`?</span>
<spanclass="go">[0, 1]</span>
<spanclass="gp">>>> </span><spanclass="n">x</span><spanclass="p">[</span><spanclass="mi">0</span><spanclass="p">]</span><spanclass="o">=</span><spanclass="o">-</span><spanclass="mi">1</span><spanclass="c1"># update one of the entries of the list that `x` references</span>
<spanclass="gp">>>> </span><spanclass="n">x</span>
<spanclass="go">[-1, 1, 2, 3]</span>
<spanclass="gp">>>> </span><spanclass="n">y</span><spanclass="c1"># the list that `y` references was unaffected by the update</span>
<spanclass="go">[0, 1]</span>
</pre></div>
</div>
<p><strong>Understanding References: Solutions</strong></p>
<p>Integers are immutable, thus <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> must reference an entirely new object (<codeclass="docutils literal notranslate"><spanclass="pre">9</span></code>), and <codeclass="docutils literal notranslate"><spanclass="pre">y</span></code> still references <codeclass="docutils literal notranslate"><spanclass="pre">3</span></code>.</p>
</div>
</div>
</div>
</div>
<footer><divclass="rst-footer-buttons" role="navigation" aria-label="Footer">
<ahref="SequenceTypes.html" class="btn btn-neutral float-left" title="Sequence Types" accesskey="p" rel="prev"><spanclass="fa fa-arrow-circle-left" aria-hidden="true"></span> Previous</a>
<ahref="Introduction.html" class="btn btn-neutral float-right" title="Introducing Control Flow" accesskey="n" rel="next">Next <spanclass="fa fa-arrow-circle-right" aria-hidden="true"></span></a>
</div>
<hr/>
<divrole="contentinfo">
<p>© Copyright 2021, Ryan Soklaski.</p>
</div>
Built with <ahref="https://www.sphinx-doc.org/">Sphinx</a> using a
<ahref="https://github.com/readthedocs/sphinx_rtd_theme">theme</a>
provided by <ahref="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script>
jQuery(function(){
SphinxRtdTheme.Navigation.enable(true);
});
</script>
</body>
</html>