{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 1.8 Iteration" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*Estimated time for this notebook: 10 minutes*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our other aspect of control is looping back on ourselves.\n", "\n", "We use `for` ... `in` to \"iterate\" over lists:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "mylist = [3, 7, 15, 2]" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9\n", "49\n", "225\n", "4\n" ] } ], "source": [ "for whatever in mylist:\n", " print(whatever**2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each time through the loop, the variable in the `value` slot is updated to the **next** element of the sequence." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1.8.1 Iterables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Any sequence type is iterable:\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'OOOkaaay'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "vowels = \"aeiou\"\n", "sarcasm = []\n", "\n", "for letter in \"Okay\":\n", " if letter.lower() in vowels:\n", " repetition = 3\n", " else:\n", " repetition = 1\n", "\n", " sarcasm.append(letter * repetition)\n", "\n", "\"\".join(sarcasm)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The above is a little puzzle, work through it to understand why it does what it does." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Dictionaries are Iterables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All sequences are iterables. Some iterables (things you can `for` loop over) are not sequences (things with you can do `x[5]` to), for example sets and dictionaries." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "In 2022 Barack Obama is 61 years old.\n", "In 2022 UCL is 195 years old.\n", "In 2022 The Alan Turing Institute is 7 years old.\n" ] } ], "source": [ "current_year = 2022\n", "founded = {\"Barack Obama\": 1961, \"UCL\": 1826, \"The Alan Turing Institute\": 2015}\n", "\n", "for thing in founded:\n", " print(f\"In {current_year} {thing} is {current_year - founded[thing]} years old.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1.8.2 Unpacking and Iteration" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Unpacking can be useful with iteration:\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "triples = [[4, 11, 15], [39, 4, 18]]" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[4, 11, 15]\n", "[39, 4, 18]\n" ] } ], "source": [ "for whatever in triples:\n", " print(whatever)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11\n", "4\n" ] } ], "source": [ "for first, middle, last in triples:\n", " print(middle)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11\n", "4\n" ] } ], "source": [ "# A reminder that the words you use for variable names are arbitrary:\n", "for hedgehog, badger, fox in triples:\n", " print(badger)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "\n", "for example, to iterate over the items in a dictionary as pairs:\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dict_items([('James', [1976, 'Kendal']), ('UCL', [1826, 'Bloomsbury']), ('Cambridge', [1209, 'Cambridge'])])\n" ] } ], "source": [ "things = {\n", " \"James\": [1976, \"Kendal\"],\n", " \"UCL\": [1826, \"Bloomsbury\"],\n", " \"Cambridge\": [1209, \"Cambridge\"],\n", "}\n", "\n", "print(things.items())" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "James is 45 years old.\n", "UCL is 195 years old.\n", "Cambridge is 812 years old.\n" ] } ], "source": [ "for name, year in founded.items():\n", " print(name, \"is\", current_year - year, \"years old.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1.8.3 Break, Continue" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "* Continue skips to the next turn of a loop\n", "* Break stops the loop early\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "3\n", "5\n", "7\n", "9\n", "11\n", "13\n", "15\n", "17\n", "19\n" ] } ], "source": [ "for n in range(50):\n", " if n == 20:\n", " break\n", " if n % 2 == 0:\n", " continue\n", " print(n)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These aren't useful that often, but are worth knowing about. There's also an optional `else` clause on loops, executed only if you don't `break`, but I've never found that useful." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "jekyll": { "display_name": "Looping" }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.8.8" } }, "nbformat": 4, "nbformat_minor": 1 }