Skip to content

Idea for more detailed list comprehension explanation #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 19, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions part-4.ipynb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"metadata": {
"name": "",
"signature": "sha256:40f96dd4a9a68767b80bf16809c2b3aebd08f6893eb2d01994fd18e611864f26"
"signature": "sha256:d806710bd05c6f416dc3842515677b9246aa116881cfd0f7dd2c6b748a3a67e5"
},
"nbformat": 3,
"nbformat_minor": 0,
Expand Down Expand Up @@ -110,13 +110,44 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Note how our list comprehension is written within the brackets: The for-loop statement is written at the end whereas the action inside of the for-loop is written first: n * n"
"Let's compare the two methods real quick by highlighting the different logical parts."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First written as a conventional 'for' loop:\n",
"<pre>\n",
"<span style=\"background:orange\">squared_numbers</span> = []\n",
"<span style=\"background:cyan\">for n in</span> <span style=\"background:yellowgreen\">my_favorite_numbers</span>:\n",
"&nbsp;&nbsp;&nbsp;&nbsp;squared_numbers.append(<span style=\"background:pink\">n * n</span>)\n",
"</pre>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And then written as a list comprehension:\n",
"<pre>\n",
"<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",
"</pre>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Improving our work\n",
"\n",
"Let's revisit a problem we've already solved in Danny's lecture on list:\n",
"\n",
"Pick every name from a list that begins with a vowel.\n",
Expand Down