|
1 | 1 | {
|
2 | 2 | "metadata": {
|
3 | 3 | "name": "",
|
4 |
| - "signature": "sha256:40f96dd4a9a68767b80bf16809c2b3aebd08f6893eb2d01994fd18e611864f26" |
| 4 | + "signature": "sha256:d806710bd05c6f416dc3842515677b9246aa116881cfd0f7dd2c6b748a3a67e5" |
5 | 5 | },
|
6 | 6 | "nbformat": 3,
|
7 | 7 | "nbformat_minor": 0,
|
|
110 | 110 | "cell_type": "markdown",
|
111 | 111 | "metadata": {},
|
112 | 112 | "source": [
|
113 |
| - "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" |
| 113 | + "Let's compare the two methods real quick by highlighting the different logical parts." |
114 | 114 | ]
|
115 | 115 | },
|
116 | 116 | {
|
117 | 117 | "cell_type": "markdown",
|
118 | 118 | "metadata": {},
|
119 | 119 | "source": [
|
| 120 | + "First written as a conventional 'for' loop:\n", |
| 121 | + "<pre>\n", |
| 122 | + "<span style=\"background:orange\">squared_numbers</span> = []\n", |
| 123 | + "<span style=\"background:cyan\">for n in</span> <span style=\"background:yellowgreen\">my_favorite_numbers</span>:\n", |
| 124 | + " squared_numbers.append(<span style=\"background:pink\">n * n</span>)\n", |
| 125 | + "</pre>" |
| 126 | + ] |
| 127 | + }, |
| 128 | + { |
| 129 | + "cell_type": "markdown", |
| 130 | + "metadata": {}, |
| 131 | + "source": [ |
| 132 | + "And then written as a list comprehension:\n", |
| 133 | + "<pre>\n", |
| 134 | + "<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", |
| 135 | + "</pre>" |
| 136 | + ] |
| 137 | + }, |
| 138 | + { |
| 139 | + "cell_type": "markdown", |
| 140 | + "metadata": {}, |
| 141 | + "source": [ |
| 142 | + "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." |
| 143 | + ] |
| 144 | + }, |
| 145 | + { |
| 146 | + "cell_type": "markdown", |
| 147 | + "metadata": {}, |
| 148 | + "source": [ |
| 149 | + "### Improving our work\n", |
| 150 | + "\n", |
120 | 151 | "Let's revisit a problem we've already solved in Danny's lecture on list:\n",
|
121 | 152 | "\n",
|
122 | 153 | "Pick every name from a list that begins with a vowel.\n",
|
|
0 commit comments