-
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>
<html class="writer-html5" lang="en" >
<head>
<meta charset="utf-8" /><meta content="Topic: the basics of iterables in python, Difficulty: Medium, Category: Section" name="description" />
<meta content="iterables, max, min, sum, all, any, itertools, enumerate, unpack" name="keywords" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Iterables — Python Like You Mean It</title>
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="../_static/my_theme.css" type="text/css" />
<!--[if lt IE 9]>
<script src="../_static/js/html5shiv.min.js"></script>
<![endif]-->
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-115029372-1"></script>
<script src="../_static/gtag.js"></script>
<script crossorigin="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>
<script defer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script src="../_static/js/theme.js"></script>
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="Generators & Comprehension Expressions" href="Generators_and_Comprehensions.html" />
<link rel="prev" title="For-Loops and While-Loops" href="ForLoops.html" />
</head>
<body class="wy-body-for-nav">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search" >
<a href="../index.html" class="icon icon-home"> Python Like You Mean It
</a>
<div class="version">
1.4
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div><div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
<p class="caption" role="heading"><span class="caption-text">Table of Contents:</span></p>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../intro.html">Python Like You Mean It</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_1.html">Module 1: Getting Started with Python</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../module_2.html">Module 2: The Essentials of Python</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="Basic_Objects.html">Basic Object Types</a></li>
<li class="toctree-l2"><a class="reference internal" href="SequenceTypes.html">Sequence Types</a></li>
<li class="toctree-l2"><a class="reference internal" href="Variables_and_Assignment.html">Variables & Assignment</a></li>
<li class="toctree-l2"><a class="reference internal" href="Introduction.html">Introducing Control Flow</a></li>
<li class="toctree-l2"><a class="reference internal" href="ConditionalStatements.html">Conditional Statements</a></li>
<li class="toctree-l2"><a class="reference internal" href="ForLoops.html">For-Loops and While-Loops</a></li>
<li class="toctree-l2 current"><a class="current reference internal" href="#">Iterables</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#Functions-that-act-on-iterables">Functions that act on iterables</a></li>
<li class="toctree-l3"><a class="reference internal" href="#Tricks-for-working-with-iterables">Tricks for working with iterables</a><ul>
<li class="toctree-l4"><a class="reference internal" href="#“Unpacking”-iterables">“Unpacking” iterables</a></li>
<li class="toctree-l4"><a class="reference internal" href="#Enumerating-iterables">Enumerating iterables</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="#Links-to-Official-Documentation">Links to Official Documentation</a></li>
<li class="toctree-l3"><a class="reference internal" href="#Reading-Comprehension-Exercise-Solutions:">Reading Comprehension Exercise Solutions:</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="Generators_and_Comprehensions.html">Generators & Comprehension Expressions</a></li>
<li class="toctree-l2"><a class="reference internal" href="Itertools.html">Python’s “Itertools”</a></li>
<li class="toctree-l2"><a class="reference internal" href="Functions.html">Basics of Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="Scope.html">Scope</a></li>
<li class="toctree-l2"><a class="reference internal" href="DataStructures.html">Data Structures (Part I): Introduction</a></li>
<li class="toctree-l2"><a class="reference internal" href="DataStructures_II_Dictionaries.html">Data Structures (Part II): Dictionaries</a></li>
<li class="toctree-l2"><a class="reference internal" href="DataStructures_III_Sets_and_More.html">Data Structures (Part III): Sets & the Collections Module</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../module_2_problems.html">Module 2: Problems</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_3.html">Module 3: The Essentials of NumPy</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_3_problems.html">Module 3: Problems</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_4.html">Module 4: Object Oriented Programming</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_5.html">Module 5: Odds and Ends</a></li>
<li class="toctree-l1"><a class="reference internal" href="../changes.html">Changelog</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"><nav class="wy-nav-top" aria-label="Mobile navigation menu" >
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../index.html">Python Like You Mean It</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="Page navigation">
<ul class="wy-breadcrumbs">
<li><a href="../index.html" class="icon icon-home"></a> »</li>
<li><a href="../module_2.html">Module 2: The Essentials of Python</a> »</li>
<li>Iterables</li>
<li class="wy-breadcrumbs-aside">
<a href="../_sources/Module2_EssentialsOfPython/Iterables.md.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="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>
<div class="section" id="Iterables">
<h1>Iterables<a class="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>
<div class="admonition note">
<p class="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>
<div class="admonition warning">
<p class="admonition-title fa fa-exclamation-circle"><strong>Note</strong>:</p>
<p>“Under the hood”, an iterable is any Python object with an <code class="docutils literal notranslate"><span class="pre">__iter__()</span></code> method or with a <code class="docutils literal notranslate"><span class="pre">__getitem__()</span></code> method that implements <code class="docutils literal notranslate"><span class="pre">Sequence</span></code> semantics. These details will become salient if you read through the Object Oriented Programming module.</p>
</div>
<div class="section" id="Functions-that-act-on-iterables">
<h2>Functions that act on iterables<a class="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>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">list</span></code>, <code class="docutils literal notranslate"><span class="pre">tuple</span></code>, <code class="docutils literal notranslate"><span class="pre">dict</span></code>, <code class="docutils literal notranslate"><span class="pre">set</span></code>: construct a list, tuple, <a class="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html">dictionary</a>, or <a class="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><code class="docutils literal notranslate"><span class="pre">sum</span></code>: sum the contents of an iterable.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">sorted</span></code>: return a list of the sorted contents of an interable</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">any</span></code>: returns <code class="docutils literal notranslate"><span class="pre">True</span></code> and ends the iteration immediately if <code class="docutils literal notranslate"><span class="pre">bool(item)</span></code> was <code class="docutils literal notranslate"><span class="pre">True</span></code> for <em>any</em> item in the iterable.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">all</span></code>: returns <code class="docutils literal notranslate"><span class="pre">True</span></code> only if <code class="docutils literal notranslate"><span class="pre">bool(item)</span></code> was <code class="docutils literal notranslate"><span class="pre">True</span></code> for <em>all</em> items in the iterable.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">max</span></code>: return the largest value in an iterable.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">min</span></code>: return the smallest value in an iterable.</p></li>
</ul>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># Examples of built-in functions that act on iterables</span>
<span class="o">>>></span> <span class="nb">list</span><span class="p">(</span><span class="s2">"I am a cow"</span><span class="p">)</span>
<span class="p">[</span><span class="s1">'I'</span><span class="p">,</span> <span class="s1">' '</span><span class="p">,</span> <span class="s1">'a'</span><span class="p">,</span> <span class="s1">'m'</span><span class="p">,</span> <span class="s1">' '</span><span class="p">,</span> <span class="s1">'a'</span><span class="p">,</span> <span class="s1">' '</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'o'</span><span class="p">,</span> <span class="s1">'w'</span><span class="p">]</span>
<span class="o">>>></span> <span class="nb">sum</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">])</span>
<span class="mi">6</span>
<span class="o">>>></span> <span class="nb">sorted</span><span class="p">(</span><span class="s2">"gheliabciou"</span><span class="p">)</span>
<span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'e'</span><span class="p">,</span> <span class="s1">'g'</span><span class="p">,</span> <span class="s1">'h'</span><span class="p">,</span> <span class="s1">'i'</span><span class="p">,</span> <span class="s1">'i'</span><span class="p">,</span> <span class="s1">'l'</span><span class="p">,</span> <span class="s1">'o'</span><span class="p">,</span> <span class="s1">'u'</span><span class="p">]</span>
<span class="c1"># `bool(item)` evaluates to `False` for each of these items</span>
<span class="o">>>></span> <span class="nb">any</span><span class="p">((</span><span class="mi">0</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="p">[],</span> <span class="mi">0</span><span class="p">))</span>
<span class="kc">False</span>
<span class="c1"># `bool(item)` evaluates to `True` for each of these items</span>
<span class="o">>>></span> <span class="nb">all</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="kc">True</span><span class="p">,</span> <span class="s2">"hi"</span><span class="p">])</span>
<span class="kc">True</span>
<span class="o">>>></span> <span class="nb">max</span><span class="p">((</span><span class="mi">5</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>
<span class="mi">9</span>
<span class="o">>>></span> <span class="nb">min</span><span class="p">(</span><span class="s2">"hello"</span><span class="p">)</span>
<span class="s1">'e'</span>
</pre></div>
</div>
</div>
<div class="section" id="Tricks-for-working-with-iterables">
<h2>Tricks for working with iterables<a class="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>
<div class="section" id="“Unpacking”-iterables">
<h3>“Unpacking” iterables<a class="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>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># simple script for assigning contents of a list to variables</span>
<span class="o">>>></span> <span class="n">my_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">7</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">11</span><span class="p">]</span>
<span class="o">>>></span> <span class="n">x</span> <span class="o">=</span> <span class="n">my_list</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="o">>>></span> <span class="n">y</span> <span class="o">=</span> <span class="n">my_list</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="o">>>></span> <span class="n">z</span> <span class="o">=</span> <span class="n">my_list</span><span class="p">[</span><span class="mi">2</span><span class="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>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># assigning contents of a list to variables using iterable unpacking</span>
<span class="o">>>></span> <span class="n">my_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">7</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">11</span><span class="p">]</span>
<span class="o">>>></span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span> <span class="o">=</span> <span class="n">my_list</span>
<span class="o">>>></span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span><span class="p">)</span>
<span class="mi">7</span> <span class="mi">9</span> <span class="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>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">grades</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">"Ashley"</span><span class="p">,</span> <span class="mi">93</span><span class="p">),</span> <span class="p">(</span><span class="s2">"Brad"</span><span class="p">,</span> <span class="mi">95</span><span class="p">),</span> <span class="p">(</span><span class="s2">"Cassie"</span><span class="p">,</span> <span class="mi">84</span><span class="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>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">entry</span> <span class="ow">in</span> <span class="n">grades</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="n">entry</span><span class="p">)</span>
</pre></div>
</div>
<p>will print:</p>
<div class="highlight-none notranslate"><div class="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 <code class="docutils literal notranslate"><span class="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 <code class="docutils literal notranslate"><span class="pre">entry</span> <span class="pre">=</span> <span class="pre">("Ashley",</span> <span class="pre">93)</span></code>, we can make use of iterable unpacking! That is, we can replace <code class="docutils literal notranslate"><span class="pre">entry</span></code> with <code class="docutils literal notranslate"><span class="pre">name,</span> <span class="pre">grade</span></code> and Python will
intuitively do an unpacking upon each assignment of the for-loop.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># The first iteration of this for-loop performs</span>
<span class="c1"># the unpacking assignment: name, grade = ("Ashley", 93)</span>
<span class="c1"># then the second iteration: name, grade = ("Brad", 95)</span>
<span class="c1"># and so-on</span>
<span class="k">for</span> <span class="n">name</span><span class="p">,</span> <span class="n">grade</span> <span class="ow">in</span> <span class="n">grades</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">grade</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"</span><span class="se">\n</span><span class="s2">"</span><span class="p">)</span>
</pre></div>
</div>
<p>prints:</p>
<div class="highlight-none notranslate"><div class="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 <a class="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>
<div class="admonition note">
<p class="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>
<div class="section" id="Enumerating-iterables">
<h3>Enumerating iterables<a class="headerlink" href="#Enumerating-iterables" title="Permalink to this headline"></a></h3>
<p>The built-in <a class="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>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># basic usage of `enumerate`</span>
<span class="o">>>></span> <span class="k">for</span> <span class="n">entry</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="s2">"abcd"</span><span class="p">):</span>
<span class="o">...</span> <span class="nb">print</span><span class="p">(</span><span class="n">entry</span><span class="p">)</span>
<span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="s1">'a'</span><span class="p">)</span>
<span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">)</span>
<span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">)</span>
<span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">)</span>
</pre></div>
</div>
<p>In general, the <code class="docutils literal notranslate"><span class="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 <code class="docutils literal notranslate"><span class="pre">None</span></code> is stored. We can achieve this by tracking the iteration count of a for-loop over the list.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># track which entries of an iterable store the value `None`</span>
<span class="n">none_indices</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">iter_cnt</span> <span class="o">=</span> <span class="mi">0</span> <span class="c1"># manually track iteration-count</span>
<span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="o">-</span><span class="mi">10</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">8</span><span class="p">]:</span>
<span class="k">if</span> <span class="n">item</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">none_indices</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">iter_cnt</span><span class="p">)</span>
<span class="n">iter_cnt</span> <span class="o">=</span> <span class="n">iter_cnt</span> <span class="o">+</span> <span class="mi">1</span>
<span class="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 <code class="docutils literal notranslate"><span class="pre">iter_cnt</span></code> variable, by utilizing <code class="docutils literal notranslate"><span class="pre">enumerate</span></code> along with tuple-unpacking.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># using the `enumerate` function to keep iteration-count</span>
<span class="n">none_indices</span> <span class="o">=</span> <span class="p">[]</span>
<span class="c1"># note the use of iterable unpacking!</span>
<span class="k">for</span> <span class="n">iter_cnt</span><span class="p">,</span> <span class="n">item</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="o">-</span><span class="mi">10</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">8</span><span class="p">]):</span>
<span class="k">if</span> <span class="n">item</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">none_indices</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">iter_cnt</span><span class="p">)</span>
<span class="c1"># `none_indices` now stores: [1, 3]</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title fa fa-exclamation-circle"><strong>Takeaway</strong>:</p>
<p>The built-in <a class="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>
<div class="admonition note">
<p class="admonition-title fa fa-exclamation-circle"><strong>Reading Comprehension: enumerate</strong></p>
<p>Use the iterable <code class="docutils literal notranslate"><span class="pre">"abcd"</span></code>, the <code class="docutils literal notranslate"><span class="pre">enumerate</span></code> function, and tuple-unpacking in a for-loop to create the list: <code class="docutils literal notranslate"><span class="pre">[(0,</span> <span class="pre">'a'),</span> <span class="pre">(1,</span> <span class="pre">'b'),</span> <span class="pre">(2,</span> <span class="pre">'c'),</span> <span class="pre">(3,</span> <span class="pre">'d')]</span></code></p>
</div>
<div class="admonition note">
<p class="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 <code class="docutils literal notranslate"><span class="pre">unsorted_index</span></code> should be initialized to <code class="docutils literal notranslate"><span class="pre">None</span></code>. If the iterable is <em>not</em> sorted, <code class="docutils literal notranslate"><span class="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 <code class="docutils literal notranslate"><span class="pre">unsorted_index</span></code> should remain <code class="docutils literal notranslate"><span class="pre">None</span></code> and your code should print “sorted!”.</p>
<p>For instance:</p>
<ul class="simple">
<li><p>given the iterable <code class="docutils literal notranslate"><span class="pre">my_list</span> <span class="pre">=</span> <span class="pre">[0,</span> <span class="pre">1,</span> <span class="pre">-10,</span> <span class="pre">2]</span></code>, <code class="docutils literal notranslate"><span class="pre">unsorted_index</span></code> should take the value <code class="docutils literal notranslate"><span class="pre">2</span></code>.</p></li>
<li><p>given the iterable <code class="docutils literal notranslate"><span class="pre">my_list</span> <span class="pre">=</span> <span class="pre">[-1,</span> <span class="pre">0,</span> <span class="pre">3,</span> <span class="pre">6]</span></code>, <code class="docutils literal notranslate"><span class="pre">unsorted_index</span></code> should be <code class="docutils literal notranslate"><span class="pre">None</span></code> and your code should print “sorted!”.</p></li>
</ul>
</div>
</div>
</div>
<div class="section" id="Links-to-Official-Documentation">
<h2>Links to Official Documentation<a class="headerlink" href="#Links-to-Official-Documentation" title="Permalink to this headline"></a></h2>
<ul class="simple">
<li><p><a class="reference external" href="https://docs.python.org/3/glossary.html#term-iterable">Iterable Definition</a></p></li>
<li><p><a class="reference external" href="https://docs.python.org/3/howto/functional.html#built-in-functions">Functions on iterables</a></p></li>
<li><p><a class="reference external" href="https://docs.python.org/3/library/functions.html#enumerate">enumerate</a></p></li>
</ul>
</div>
<div class="section" id="Reading-Comprehension-Exercise-Solutions:">
<h2>Reading Comprehension Exercise Solutions:<a class="headerlink" href="#Reading-Comprehension-Exercise-Solutions:" title="Permalink to this headline"></a></h2>
<p><strong>enumerate: Solution</strong></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">out</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">num</span><span class="p">,</span> <span class="n">letter</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="s2">"abcd"</span><span class="p">):</span>
<span class="n">out</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">num</span><span class="p">,</span> <span class="n">letter</span><span class="p">))</span>
</pre></div>
</div>
<p><strong>Is it sorted?: Solution</strong></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">my_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">10</span><span class="p">,</span> <span class="mi">2</span><span class="p">]</span>
<span class="n">unsorted_index</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">for</span> <span class="n">index</span><span class="p">,</span> <span class="n">current_num</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">my_list</span><span class="p">):</span>
<span class="k">if</span> <span class="n">index</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="n">prev_num</span> <span class="o">=</span> <span class="n">current_num</span>
<span class="k">elif</span> <span class="n">prev_num</span> <span class="o">></span> <span class="n">current_num</span><span class="p">:</span>
<span class="n">unsorted_index</span> <span class="o">=</span> <span class="n">index</span>
<span class="k">break</span>
<span class="n">prev_num</span> <span class="o">=</span> <span class="n">current_num</span>
<span class="k">else</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"sorted!"</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
<footer><div class="rst-footer-buttons" role="navigation" aria-label="Footer">
<a href="ForLoops.html" class="btn btn-neutral float-left" title="For-Loops and While-Loops" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left" aria-hidden="true"></span> Previous</a>
<a href="Generators_and_Comprehensions.html" class="btn btn-neutral float-right" title="Generators & Comprehension Expressions" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right" aria-hidden="true"></span></a>
</div>
<hr/>
<div role="contentinfo">
<p>© Copyright 2021, Ryan Soklaski.</p>
</div>
Built with <a href="https://www.sphinx-doc.org/">Sphinx</a> using a
<a href="https://github.com/readthedocs/sphinx_rtd_theme">theme</a>
provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script>
jQuery(function () {
SphinxRtdTheme.Navigation.enable(true);
});
</script>
</body>
</html>