- Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathIterables.html
382 lines (347 loc) · 35.6 KB
/
Iterables.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
<!DOCTYPE html>
<htmlclass="writer-html5" lang="en" >
<head>
<metacharset="utf-8" /><metacontent="Topic: the basics of iterables in python, Difficulty: Medium, Category: Section" name="description" />
<metacontent="iterables, max, min, sum, all, any, itertools, enumerate, unpack" name="keywords" />
<metaname="viewport" content="width=device-width, initial-scale=1.0" />
<title>Iterables — 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="Generators & Comprehension Expressions" href="Generators_and_Comprehensions.html" />
<linkrel="prev" title="For-Loops and While-Loops" href="ForLoops.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"><aclass="reference internal" href="Variables_and_Assignment.html">Variables & Assignment</a></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 current"><aclass="current reference internal" href="#">Iterables</a><ul>
<liclass="toctree-l3"><aclass="reference internal" href="#Functions-that-act-on-iterables">Functions that act on iterables</a></li>
<liclass="toctree-l3"><aclass="reference internal" href="#Tricks-for-working-with-iterables">Tricks for working with iterables</a><ul>
<liclass="toctree-l4"><aclass="reference internal" href="#“Unpacking”-iterables">“Unpacking” iterables</a></li>
<liclass="toctree-l4"><aclass="reference internal" href="#Enumerating-iterables">Enumerating iterables</a></li>
</ul>
</li>
<liclass="toctree-l3"><aclass="reference internal" href="#Links-to-Official-Documentation">Links to Official Documentation</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="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>Iterables</li>
<liclass="wy-breadcrumbs-aside">
<ahref="../_sources/Module2_EssentialsOfPython/Iterables.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="Iterables">
<h1>Iterables<aclass="headerlink" href="#Iterables" title="Permalink to this headline"></a></h1>
<p>Our encounter with for-loops introduced the term <em>iterable</em> - an object that can be “iterated over”, such as in a for-loop.</p>
<divclass="admonition note">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Definition</strong>:</p>
<p>An <strong>iterable</strong> is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for-loop.</p>
</div>
<p>Familiar examples of iterables include lists, tuples, and strings - any such sequence can be iterated over in a for-loop. We will also encounter important non-sequential collections, like dictionaries and sets; these are iterables as well. It is also possible to have an iterable that “generates” each one of its members upon iteration - meaning that it doesn’t ever store all of its members in memory at once. We dedicate an entire section to generators, a special type of iterator, because they are
so useful for writing efficient code.</p>
<p>The rest of this section is dedicated to working with iterables in your code.</p>
<divclass="admonition warning">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Note</strong>:</p>
<p>“Under the hood”, an iterable is any Python object with an <codeclass="docutils literal notranslate"><spanclass="pre">__iter__()</span></code> method or with a <codeclass="docutils literal notranslate"><spanclass="pre">__getitem__()</span></code> method that implements <codeclass="docutils literal notranslate"><spanclass="pre">Sequence</span></code> semantics. These details will become salient if you read through the Object Oriented Programming module.</p>
</div>
<divclass="section" id="Functions-that-act-on-iterables">
<h2>Functions that act on iterables<aclass="headerlink" href="#Functions-that-act-on-iterables" title="Permalink to this headline"></a></h2>
<p>Here are some useful built-in functions that accept iterables as arguments:</p>
<ulclass="simple">
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">list</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">tuple</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">dict</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">set</span></code>: construct a list, tuple, <aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html">dictionary</a>, or <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">set</a>, respectively, from the contents of an iterable</p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">sum</span></code>: sum the contents of an iterable.</p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">sorted</span></code>: return a list of the sorted contents of an interable</p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">any</span></code>: returns <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> and ends the iteration immediately if <codeclass="docutils literal notranslate"><spanclass="pre">bool(item)</span></code> was <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> for <em>any</em> item in the iterable.</p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">all</span></code>: returns <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> only if <codeclass="docutils literal notranslate"><spanclass="pre">bool(item)</span></code> was <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> for <em>all</em> items in the iterable.</p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">max</span></code>: return the largest value in an iterable.</p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">min</span></code>: return the smallest value in an iterable.</p></li>
</ul>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># Examples of built-in functions that act on iterables</span>
<spanclass="o">>>></span><spanclass="nb">list</span><spanclass="p">(</span><spanclass="s2">"I am a cow"</span><spanclass="p">)</span>
<spanclass="p">[</span><spanclass="s1">'I'</span><spanclass="p">,</span><spanclass="s1">' '</span><spanclass="p">,</span><spanclass="s1">'a'</span><spanclass="p">,</span><spanclass="s1">'m'</span><spanclass="p">,</span><spanclass="s1">' '</span><spanclass="p">,</span><spanclass="s1">'a'</span><spanclass="p">,</span><spanclass="s1">' '</span><spanclass="p">,</span><spanclass="s1">'c'</span><spanclass="p">,</span><spanclass="s1">'o'</span><spanclass="p">,</span><spanclass="s1">'w'</span><spanclass="p">]</span>
<spanclass="o">>>></span><spanclass="nb">sum</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="mi">6</span>
<spanclass="o">>>></span><spanclass="nb">sorted</span><spanclass="p">(</span><spanclass="s2">"gheliabciou"</span><spanclass="p">)</span>
<spanclass="p">[</span><spanclass="s1">'a'</span><spanclass="p">,</span><spanclass="s1">'b'</span><spanclass="p">,</span><spanclass="s1">'c'</span><spanclass="p">,</span><spanclass="s1">'e'</span><spanclass="p">,</span><spanclass="s1">'g'</span><spanclass="p">,</span><spanclass="s1">'h'</span><spanclass="p">,</span><spanclass="s1">'i'</span><spanclass="p">,</span><spanclass="s1">'i'</span><spanclass="p">,</span><spanclass="s1">'l'</span><spanclass="p">,</span><spanclass="s1">'o'</span><spanclass="p">,</span><spanclass="s1">'u'</span><spanclass="p">]</span>
<spanclass="c1"># `bool(item)` evaluates to `False` for each of these items</span>
<spanclass="o">>>></span><spanclass="nb">any</span><spanclass="p">((</span><spanclass="mi">0</span><spanclass="p">,</span><spanclass="kc">None</span><spanclass="p">,</span><spanclass="p">[],</span><spanclass="mi">0</span><spanclass="p">))</span>
<spanclass="kc">False</span>
<spanclass="c1"># `bool(item)` evaluates to `True` for each of these items</span>
<spanclass="o">>>></span><spanclass="nb">all</span><spanclass="p">([</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="p">(</span><spanclass="mi">0</span><spanclass="p">,</span><spanclass="mi">1</span><spanclass="p">),</span><spanclass="kc">True</span><spanclass="p">,</span><spanclass="s2">"hi"</span><spanclass="p">])</span>
<spanclass="kc">True</span>
<spanclass="o">>>></span><spanclass="nb">max</span><spanclass="p">((</span><spanclass="mi">5</span><spanclass="p">,</span><spanclass="mi">8</span><spanclass="p">,</span><spanclass="mi">9</span><spanclass="p">,</span><spanclass="mi">0</span><spanclass="p">))</span>
<spanclass="mi">9</span>
<spanclass="o">>>></span><spanclass="nb">min</span><spanclass="p">(</span><spanclass="s2">"hello"</span><spanclass="p">)</span>
<spanclass="s1">'e'</span>
</pre></div>
</div>
</div>
<divclass="section" id="Tricks-for-working-with-iterables">
<h2>Tricks for working with iterables<aclass="headerlink" href="#Tricks-for-working-with-iterables" title="Permalink to this headline"></a></h2>
<p>Python provides some syntactic “tricks” for working with iterables: “unpacking” iterables and “enumerating” iterables. Although these may seem like inconsequential niceties at first glance, they deserve our attention because they will help us write clean, readable code. Writing clean, readable code leads to bug-free algorithms that are easy to understand. Furthermore, these tricks will also facilitate the use of other great Python features, like comprehension-statements, which will be introduced
in the coming sections.</p>
<divclass="section" id="“Unpacking”-iterables">
<h3>“Unpacking” iterables<aclass="headerlink" href="#“Unpacking”-iterables" title="Permalink to this headline"></a></h3>
<p>Suppose that you have three values stored in a list, and that you want to assign each value to a distinct variable. Given the lessons that we have covered thus far, you would likely write the following code:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># simple script for assigning contents of a list to variables</span>
<spanclass="o">>>></span><spanclass="n">my_list</span><spanclass="o">=</span><spanclass="p">[</span><spanclass="mi">7</span><spanclass="p">,</span><spanclass="mi">9</span><spanclass="p">,</span><spanclass="mi">11</span><spanclass="p">]</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="o">=</span><spanclass="n">my_list</span><spanclass="p">[</span><spanclass="mi">0</span><spanclass="p">]</span>
<spanclass="o">>>></span><spanclass="n">y</span><spanclass="o">=</span><spanclass="n">my_list</span><spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">]</span>
<spanclass="o">>>></span><spanclass="n">z</span><spanclass="o">=</span><spanclass="n">my_list</span><spanclass="p">[</span><spanclass="mi">2</span><spanclass="p">]</span>
</pre></div>
</div>
<p>Python provides an extremely useful functionality, known as <strong>iterable unpacking</strong>, which allows us to write the simple, elegant code:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># assigning contents of a list to variables using iterable unpacking</span>
<spanclass="o">>>></span><spanclass="n">my_list</span><spanclass="o">=</span><spanclass="p">[</span><spanclass="mi">7</span><spanclass="p">,</span><spanclass="mi">9</span><spanclass="p">,</span><spanclass="mi">11</span><spanclass="p">]</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="p">,</span><spanclass="n">y</span><spanclass="p">,</span><spanclass="n">z</span><spanclass="o">=</span><spanclass="n">my_list</span>
<spanclass="o">>>></span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">x</span><spanclass="p">,</span><spanclass="n">y</span><spanclass="p">,</span><spanclass="n">z</span><spanclass="p">)</span>
<spanclass="mi">7</span><spanclass="mi">9</span><spanclass="mi">11</span>
</pre></div>
</div>
<p>That is, the Python interpreter “sees” the pattern of variables to the left of the assignment, and will “unpack” the iterable (which happens to be a list in this instance). It may not seem like it from this example, but this is an <em>extremely</em> useful feature of Python that greatly improves the readability of code!</p>
<p>Iterable unpacking is particularly useful in the context of performing for-loops over iterables-of-iterables. For example, suppose we have a list containing tuples of name-grade pairs:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="n">grades</span><spanclass="o">=</span><spanclass="p">[(</span><spanclass="s2">"Ashley"</span><spanclass="p">,</span><spanclass="mi">93</span><spanclass="p">),</span><spanclass="p">(</span><spanclass="s2">"Brad"</span><spanclass="p">,</span><spanclass="mi">95</span><spanclass="p">),</span><spanclass="p">(</span><spanclass="s2">"Cassie"</span><spanclass="p">,</span><spanclass="mi">84</span><spanclass="p">)]</span>
</pre></div>
</div>
<p>Recall from the preceding section that if we loop over this list, that the iterate-variable will be assigned to each of these tuples:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="k">for</span><spanclass="n">entry</span><spanclass="ow">in</span><spanclass="n">grades</span><spanclass="p">:</span>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">entry</span><spanclass="p">)</span>
</pre></div>
</div>
<p>will print:</p>
<divclass="highlight-none notranslate"><divclass="highlight"><pre><span></span>('Ashley', 93)
('Brad', 95)
('Cassie', 84)
</pre></div>
</div>
<p>It is likely that we will want to work with the student’s name and their grade independently (e.g. use the name to access a log, and add the grade-value to our class statistics); thus we will need to index into <codeclass="docutils literal notranslate"><spanclass="pre">entry</span></code> twice to assign its contents to two separate variables. However, because each iteration of the for-loop involves an assignment of the form <codeclass="docutils literal notranslate"><spanclass="pre">entry</span><spanclass="pre">=</span><spanclass="pre">("Ashley",</span><spanclass="pre">93)</span></code>, we can make use of iterable unpacking! That is, we can replace <codeclass="docutils literal notranslate"><spanclass="pre">entry</span></code> with <codeclass="docutils literal notranslate"><spanclass="pre">name,</span><spanclass="pre">grade</span></code> and Python will
intuitively do an unpacking upon each assignment of the for-loop.</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># The first iteration of this for-loop performs</span>
<spanclass="c1"># the unpacking assignment: name, grade = ("Ashley", 93)</span>
<spanclass="c1"># then the second iteration: name, grade = ("Brad", 95)</span>
<spanclass="c1"># and so-on</span>
<spanclass="k">for</span><spanclass="n">name</span><spanclass="p">,</span><spanclass="n">grade</span><spanclass="ow">in</span><spanclass="n">grades</span><spanclass="p">:</span>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">name</span><spanclass="p">)</span>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">grade</span><spanclass="p">)</span>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="s2">"</span><spanclass="se">\n</span><spanclass="s2">"</span><spanclass="p">)</span>
</pre></div>
</div>
<p>prints:</p>
<divclass="highlight-none notranslate"><divclass="highlight"><pre><span></span>Ashley
93
Brad
95
Cassie
84
</pre></div>
</div>
<p>This for-loop code is concise and supremely readable. It is highly recommended that you make use of iterable unpacking in such contexts.</p>
<p>Iterable unpacking is not quite as simple as it might seem. What happens if you provide 4 variables to unpack into, but use an iterable containing 10 items? Although what we have covered thus far conveys the most essential use case, it is good to know that <aclass="reference external" href="https://www.python.org/dev/peps/pep-3132/#specification">Python provides an even more extensive syntax for unpacking iterables</a>. We will also see that unpacking can be useful when creating and using functions.</p>
<divclass="admonition note">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Takeaway</strong>:</p>
<p>Python provides a sleek syntax for “unpacking” the contents of an iterable - assigning each item to its own variable. This allows us to write intuitive, highly-readable code when performing a for-loop over a collection of iterables.</p>
</div>
</div>
<divclass="section" id="Enumerating-iterables">
<h3>Enumerating iterables<aclass="headerlink" href="#Enumerating-iterables" title="Permalink to this headline"></a></h3>
<p>The built-in <aclass="reference external" href="https://docs.python.org/3/library/functions.html#enumerate">enumerate</a> function allows us to iterate over an iterable, while keeping track of the iteration count:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># basic usage of `enumerate`</span>
<spanclass="o">>>></span><spanclass="k">for</span><spanclass="n">entry</span><spanclass="ow">in</span><spanclass="nb">enumerate</span><spanclass="p">(</span><spanclass="s2">"abcd"</span><spanclass="p">):</span>
<spanclass="o">...</span><spanclass="nb">print</span><spanclass="p">(</span><spanclass="n">entry</span><spanclass="p">)</span>
<spanclass="p">(</span><spanclass="mi">0</span><spanclass="p">,</span><spanclass="s1">'a'</span><spanclass="p">)</span>
<spanclass="p">(</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="s1">'b'</span><spanclass="p">)</span>
<spanclass="p">(</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="s1">'c'</span><spanclass="p">)</span>
<spanclass="p">(</span><spanclass="mi">3</span><spanclass="p">,</span><spanclass="s1">'d'</span><spanclass="p">)</span>
</pre></div>
</div>
<p>In general, the <codeclass="docutils literal notranslate"><spanclass="pre">enumerate</span></code> function accepts an iterable as an input, and returns a new iterable that produces a tuple of the iteration-count and the corresponding item from the original iterable. Thus the items in the iterable are being enumerated. To see the utility of this, suppose that we want to record all of the positions in a list where the value <codeclass="docutils literal notranslate"><spanclass="pre">None</span></code> is stored. We can achieve this by tracking the iteration count of a for-loop over the list.</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># track which entries of an iterable store the value `None`</span>
<spanclass="n">none_indices</span><spanclass="o">=</span><spanclass="p">[]</span>
<spanclass="n">iter_cnt</span><spanclass="o">=</span><spanclass="mi">0</span><spanclass="c1"># manually track iteration-count</span>
<spanclass="k">for</span><spanclass="n">item</span><spanclass="ow">in</span><spanclass="p">[</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="kc">None</span><spanclass="p">,</span><spanclass="o">-</span><spanclass="mi">10</span><spanclass="p">,</span><spanclass="kc">None</span><spanclass="p">,</span><spanclass="mi">4</span><spanclass="p">,</span><spanclass="mi">8</span><spanclass="p">]:</span>
<spanclass="k">if</span><spanclass="n">item</span><spanclass="ow">is</span><spanclass="kc">None</span><spanclass="p">:</span>
<spanclass="n">none_indices</span><spanclass="o">.</span><spanclass="n">append</span><spanclass="p">(</span><spanclass="n">iter_cnt</span><spanclass="p">)</span>
<spanclass="n">iter_cnt</span><spanclass="o">=</span><spanclass="n">iter_cnt</span><spanclass="o">+</span><spanclass="mi">1</span>
<spanclass="c1"># `none_indices` now stores: [1, 3]</span>
</pre></div>
</div>
<p>We can simplify this code, and avoid having to initialize or increment the <codeclass="docutils literal notranslate"><spanclass="pre">iter_cnt</span></code> variable, by utilizing <codeclass="docutils literal notranslate"><spanclass="pre">enumerate</span></code> along with tuple-unpacking.</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># using the `enumerate` function to keep iteration-count</span>
<spanclass="n">none_indices</span><spanclass="o">=</span><spanclass="p">[]</span>
<spanclass="c1"># note the use of iterable unpacking!</span>
<spanclass="k">for</span><spanclass="n">iter_cnt</span><spanclass="p">,</span><spanclass="n">item</span><spanclass="ow">in</span><spanclass="nb">enumerate</span><spanclass="p">([</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="kc">None</span><spanclass="p">,</span><spanclass="o">-</span><spanclass="mi">10</span><spanclass="p">,</span><spanclass="kc">None</span><spanclass="p">,</span><spanclass="mi">4</span><spanclass="p">,</span><spanclass="mi">8</span><spanclass="p">]):</span>
<spanclass="k">if</span><spanclass="n">item</span><spanclass="ow">is</span><spanclass="kc">None</span><spanclass="p">:</span>
<spanclass="n">none_indices</span><spanclass="o">.</span><spanclass="n">append</span><spanclass="p">(</span><spanclass="n">iter_cnt</span><spanclass="p">)</span>
<spanclass="c1"># `none_indices` now stores: [1, 3]</span>
</pre></div>
</div>
<divclass="admonition note">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Takeaway</strong>:</p>
<p>The built-in <aclass="reference external" href="https://docs.python.org/3/library/functions.html#enumerate">enumerate</a> function should be used (in conjunction with iterator unpacking) whenever it is necessary to track the iteration count of a for-loop. It is valuable to use this in conjunction with tuple unpacking.</p>
</div>
<divclass="admonition note">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Reading Comprehension: enumerate</strong></p>
<p>Use the iterable <codeclass="docutils literal notranslate"><spanclass="pre">"abcd"</span></code>, the <codeclass="docutils literal notranslate"><spanclass="pre">enumerate</span></code> function, and tuple-unpacking in a for-loop to create the list: <codeclass="docutils literal notranslate"><spanclass="pre">[(0,</span><spanclass="pre">'a'),</span><spanclass="pre">(1,</span><spanclass="pre">'b'),</span><spanclass="pre">(2,</span><spanclass="pre">'c'),</span><spanclass="pre">(3,</span><spanclass="pre">'d')]</span></code></p>
</div>
<divclass="admonition note">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Reading Comprehension: Is it sorted?</strong></p>
<p>Use control flow and looping tools to see if an iterable of numbers is sorted.</p>
<p>The variable <codeclass="docutils literal notranslate"><spanclass="pre">unsorted_index</span></code> should be initialized to <codeclass="docutils literal notranslate"><spanclass="pre">None</span></code>. If the iterable is <em>not</em> sorted, <codeclass="docutils literal notranslate"><spanclass="pre">unsorted_index</span></code> should store the index where the sequence <em>first</em> fell out of order. If the iterable is sorted, then <codeclass="docutils literal notranslate"><spanclass="pre">unsorted_index</span></code> should remain <codeclass="docutils literal notranslate"><spanclass="pre">None</span></code> and your code should print “sorted!”.</p>
<p>For instance:</p>
<ulclass="simple">
<li><p>given the iterable <codeclass="docutils literal notranslate"><spanclass="pre">my_list</span><spanclass="pre">=</span><spanclass="pre">[0,</span><spanclass="pre">1,</span><spanclass="pre">-10,</span><spanclass="pre">2]</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">unsorted_index</span></code> should take the value <codeclass="docutils literal notranslate"><spanclass="pre">2</span></code>.</p></li>
<li><p>given the iterable <codeclass="docutils literal notranslate"><spanclass="pre">my_list</span><spanclass="pre">=</span><spanclass="pre">[-1,</span><spanclass="pre">0,</span><spanclass="pre">3,</span><spanclass="pre">6]</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">unsorted_index</span></code> should be <codeclass="docutils literal notranslate"><spanclass="pre">None</span></code> and your code should print “sorted!”.</p></li>
</ul>
</div>
</div>
</div>
<divclass="section" id="Links-to-Official-Documentation">
<h2>Links to Official Documentation<aclass="headerlink" href="#Links-to-Official-Documentation" title="Permalink to this headline"></a></h2>
<ulclass="simple">
<li><p><aclass="reference external" href="https://docs.python.org/3/glossary.html#term-iterable">Iterable Definition</a></p></li>
<li><p><aclass="reference external" href="https://docs.python.org/3/howto/functional.html#built-in-functions">Functions on iterables</a></p></li>
<li><p><aclass="reference external" href="https://docs.python.org/3/library/functions.html#enumerate">enumerate</a></p></li>
</ul>
</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>enumerate: Solution</strong></p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="n">out</span><spanclass="o">=</span><spanclass="p">[]</span>
<spanclass="k">for</span><spanclass="n">num</span><spanclass="p">,</span><spanclass="n">letter</span><spanclass="ow">in</span><spanclass="nb">enumerate</span><spanclass="p">(</span><spanclass="s2">"abcd"</span><spanclass="p">):</span>
<spanclass="n">out</span><spanclass="o">.</span><spanclass="n">append</span><spanclass="p">((</span><spanclass="n">num</span><spanclass="p">,</span><spanclass="n">letter</span><spanclass="p">))</span>
</pre></div>
</div>
<p><strong>Is it sorted?: Solution</strong></p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="n">my_list</span><spanclass="o">=</span><spanclass="p">[</span><spanclass="mi">0</span><spanclass="p">,</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="o">-</span><spanclass="mi">10</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">]</span>
<spanclass="n">unsorted_index</span><spanclass="o">=</span><spanclass="kc">None</span>
<spanclass="k">for</span><spanclass="n">index</span><spanclass="p">,</span><spanclass="n">current_num</span><spanclass="ow">in</span><spanclass="nb">enumerate</span><spanclass="p">(</span><spanclass="n">my_list</span><spanclass="p">):</span>
<spanclass="k">if</span><spanclass="n">index</span><spanclass="o">==</span><spanclass="mi">0</span><spanclass="p">:</span>
<spanclass="n">prev_num</span><spanclass="o">=</span><spanclass="n">current_num</span>
<spanclass="k">elif</span><spanclass="n">prev_num</span><spanclass="o">></span><spanclass="n">current_num</span><spanclass="p">:</span>
<spanclass="n">unsorted_index</span><spanclass="o">=</span><spanclass="n">index</span>
<spanclass="k">break</span>
<spanclass="n">prev_num</span><spanclass="o">=</span><spanclass="n">current_num</span>
<spanclass="k">else</span><spanclass="p">:</span>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="s2">"sorted!"</span><spanclass="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
<footer><divclass="rst-footer-buttons" role="navigation" aria-label="Footer">
<ahref="ForLoops.html" class="btn btn-neutral float-left" title="For-Loops and While-Loops" accesskey="p" rel="prev"><spanclass="fa fa-arrow-circle-left" aria-hidden="true"></span> Previous</a>
<ahref="Generators_and_Comprehensions.html" class="btn btn-neutral float-right" title="Generators & Comprehension Expressions" 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>