Skip to content

Commit 5c714c3

Browse files
macro1willingc
authored andcommitted
Highlight example between for loop and list comprehension
Fixes #17 Author: Micah Denbraver <[email protected]>
1 parent 77335b7 commit 5c714c3

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

part-4.ipynb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,12 +111,44 @@
111111
"metadata": {},
112112
"source": [
113113
"Note how our list comprehension is written within the brackets: The list we're looping over (my_favorite_numbers) is written at the end whereas the action inside of the for-loop is written first: n * n"
114+
"Let's compare the two methods real quick by highlighting the different logical parts."
114115
]
115116
},
116117
{
117118
"cell_type": "markdown",
118119
"metadata": {},
119120
"source": [
121+
"First written as a conventional 'for' loop:\n",
122+
"<pre>\n",
123+
"<span style=\"background:orange\">squared_numbers</span> = []\n",
124+
"<span style=\"background:cyan\">for n in</span> <span style=\"background:yellowgreen\">my_favorite_numbers</span>:\n",
125+
"&nbsp;&nbsp;&nbsp;&nbsp;squared_numbers.append(<span style=\"background:pink\">n * n</span>)\n",
126+
"</pre>"
127+
]
128+
},
129+
{
130+
"cell_type": "markdown",
131+
"metadata": {},
132+
"source": [
133+
"And then written as a list comprehension:\n",
134+
"<pre>\n",
135+
"<span style=\"background:orange\">squared_numbers</span> = [<span style=\"background:pink\">n * n</span> <span style=\"background:cyan\">for n in</span> <span style=\"background:yellowgreen\">my_favorite_numbers</span>]\n",
136+
"</pre>"
137+
]
138+
},
139+
{
140+
"cell_type": "markdown",
141+
"metadata": {},
142+
"source": [
143+
"Look for the <span style=\"background:orange\">new list</span> being created, the <span style=\"background:cyan\">iteration</span> being done over the <span style=\"background:yellowgreen\">orignal list</span> and the <span style=\"background:pink\">transformation</span> being done on each element. List comprehensions are just a cleaner way of building lists from other iterables."
144+
]
145+
},
146+
{
147+
"cell_type": "markdown",
148+
"metadata": {},
149+
"source": [
150+
"### Improving our work\n",
151+
"\n",
120152
"Let's revisit a problem we've already solved in Danny's lecture on lists:\n",
121153
"\n",
122154
"Pick every name from a list that begins with a vowel.\n",

0 commit comments

Comments
 (0)