{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Module 2\n", "\n", "## Video 7: Generating Lists\n", "**Python for the Energy Industry**\n", "\n", "It's common to make a list by conditionally appending inside a loop. See this example of making a list of even numbers:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 2, 4, 6, 8, 10]\n" ] } ], "source": [ "evens = []\n", "\n", "for i in range(11):\n", " if i % 2 == 0:\n", " evens.append(i)\n", " \n", "print(evens)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's another example, of finding the words in a list beginning with A:\n", "\n", "*Note: strings can be treated in many ways as a list of characters - see below how we access the first letter of word as word[0]*" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['AARDVARK', 'APPLE', 'ARROW']\n" ] } ], "source": [ "words = ['AARDVARK','APPLE','ARROW','BARN','CACTUS']\n", "a_words = []\n", "\n", "for word in words:\n", " if word[0] == 'A':\n", " a_words.append(word)\n", " \n", "print(a_words)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This procedure is so common that there is a Python shorthand for it, called the 'list comprehension' which takes the form:\n", "\n", "``` new_list = [item for item in old_list if condition] ``` \n", "\n", "Here's how this looks for our even numbers example:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 2, 4, 6, 8, 10]\n" ] } ], "source": [ "evens = [i for i in range(11) if i % 2 == 0]\n", "\n", "print(evens)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also apply a function onto the item before storing it in the list. We will cover functions in more detail later, but here is a simple example:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 4, 16, 36, 64]\n" ] } ], "source": [ "squares = [i**2 for i in range(10) if i % 2 == 0]\n", "\n", "print(squares)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise\n", "\n", "Try to write the list comprehension corresponding to our A words example." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.9" } }, "nbformat": 4, "nbformat_minor": 4 }