{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python Variables, Including Lists and Tuples, and Arrays from Package Numpy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This work is licensed under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/)\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Foreword\n",
    "\n",
    "With this and all future sections, start by creating your own Jupyter notebook;\n",
    "perhaps by copying relevant cells from this notebook and then adding your work.\n",
    "\n",
    "If you also wish to start practicing with the Spyder IDE, then in addition use it to create a Python code file with that code, and run the commands there too.\n",
    "\n",
    "Later you might find it preferable to develop code in Spyder and then copy the working code and notes into a notebook for final presentation — Spyder has better tools for debugging."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Numerical variables\n",
    "\n",
    "The first step beyond using Python merely as a calculator is storing value in variables, for reuse later in more elaborate calculations.\n",
    "For example, to find both roots of a quadratic equation\n",
    "\n",
    "$$ax^2 + bx + c = 0$$\n",
    "\n",
    "we want the values of each coefficient and are going to use each of them twice, which we might want to do without typing in each coefficient twice over."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example\n",
    "\n",
    "We can solve the specific equation\n",
    "\n",
    "$$2x^2 - 8x + 6 = 0$$\n",
    "\n",
    "using the quadratic formula.\n",
    "But first we need to get the square root function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import sqrt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then the rest looks almost like normal mathematical notation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 2\n",
    "b = -10\n",
    "c = 8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "root0 = (-b - sqrt(b**2 - 4 * a * c))/(2 * a)\n",
    "root1 = (-b + sqrt(b**2 - 4 * a * c))/(2 * a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(Aside: why did I number the roots 0 and 1 instead of 1 and 2?  The answer is coming up soon.)\n",
    "\n",
    "Where are the results?  They have been stored in variables rather than printed out, so to see them, use the <code>print</code> function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The smaller root is 1.0 and the larger root is 4.0\n"
     ]
    }
   ],
   "source": [
    "print('The smaller root is', root0, 'and the larger root is', root1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Aside:** This is the first mention of the function `print`, for output to the screen (or to files).\n",
    "You can probably learn enough about its usage from examples in this and subsequent units of the course, but for more information see also the notes on\n",
    "{doc}`Formatted Output and Some Text String Manipulation <formatted-output-and-some-text-string-manipulation>`\n",
    "\n",
    "[Formatted Output and Some Text String Manipulation](formatted-output-and-some-text-string-manipulation.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A short-cut for printing the value of a variable is to simply enter its name on th last line of a cell:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.0"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "root0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also do this for multiple variables, as with: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1.0, 4.0)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "root0, root1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the output is parenthesized: this, as will be explained below, is a {ref}`tuple <tuples>`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Text variables\n",
    "\n",
    "Other information can be put into variables, such as strings of text:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, my name is Brenton LeMesurier\n"
     ]
    }
   ],
   "source": [
    "LastName = \"LeMesurier\"\n",
    "FirstName = 'Brenton'\n",
    "print(\"Hello, my name is\", FirstName, LastName)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that either 'single quotes' or \"double quotes\" can be use to surround text, but one must be consistent within each piece of text.\n",
    "I recomned always uising double quotes (which are true quotation characters) not single quotes (which are actually apostrophes:\n",
    "for one thing many other languages require this, so it could help to get into the habit."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Lists\n",
    "\n",
    "Python has several ways of grouping together information into one variable.\n",
    "We first look at *lists*, which can collect all kinds of information together:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, -10, 8] ['LeMesurier', 'Brenton'] [9535917]\n"
     ]
    }
   ],
   "source": [
    "coefficients = [2, -10, 8]\n",
    "name = [\"LeMesurier\", \"Brenton\"]\n",
    "phone = [9535917]\n",
    "print(coefficients, name, phone)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Lists can be combined by \"addition\", which is concatenation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['LeMesurier', 'Brenton', 9535917]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "name + phone"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Individual entries (\"elements\") can be extracted from lists; note that **Python always counts from 0**,\n",
    "and indices go in [brackets], not (parentheses) or {braces}:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Brenton LeMesurier\n"
     ]
    }
   ],
   "source": [
    "LastName = name[0]\n",
    "FirstName = name[1]\n",
    "print(FirstName, LastName)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and we can modify list elements this way too:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "John\n",
      "['LeMesurier', 'John']\n"
     ]
    }
   ],
   "source": [
    "name[1] = 'John'\n",
    "print(name[1])\n",
    "print(name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can use the list of coefficients to specify the quadratic, and store both roots in a new list.\n",
    "\n",
    "But let's shorten the name first, by making \"q\" a synonym for \"coefficients\":"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The list of coefficients is [2, -10, 8]\n"
     ]
    }
   ],
   "source": [
    "q = coefficients\n",
    "print('The list of coefficients is', q)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The list of roots is [1.0, 4.0]\n",
      "The individual roots are 1.0 and 4.0\n"
     ]
    }
   ],
   "source": [
    "roots = [(-q[1] - sqrt(q[1]**2 - 4 * q[0] * q[2]))/(2 * q[0]),\n",
    "         (-q[1] + sqrt(q[1]**2 - 4 * q[0] * q[2]))/(2 * q[0])]\n",
    "print('The list of roots is', roots)\n",
    "print('The individual roots are', roots[0], 'and', roots[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "See now why I enumerated the roots from 0 previously?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For readability, you might want to \"unpack\" the coefficients by copying into individual variables, and then use the more familiar formulas above:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = q[0]\n",
    "b = q[1]\n",
    "c = q[2]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Alternatively one can unpack the elements of a list into separate variables with"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "(a, b, c) = q"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The list of roots is again [1.0, 4.0]\n"
     ]
    }
   ],
   "source": [
    "roots = [(-b - sqrt(b**2 - 4 * a * c))/(2 * a),\n",
    "         (-b + sqrt(b**2 - 4 * a * c))/(2 * a)]\n",
    "print('The list of roots is again', roots)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The equals sign `=` creates *synonyms* for lists; not copies\n",
    "\n",
    "Note that it says above that the statement `q = coefficients` makes `q` is a *synonym* for `coefficients`, not a copy of its values.\n",
    "To see this, note that when we make a change to `q` it also applies to `coefficients` (and vice versa):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "q is [2, -10, 8]\n",
      "coefficients is [2, -10, 8]\n",
      "q is now [4, -10, 8]\n",
      "coefficients is now [4, -10, 8]\n"
     ]
    }
   ],
   "source": [
    "print(\"q is\", q)\n",
    "print(\"coefficients is\", coefficients)\n",
    "q[0] = 4\n",
    "print(\"q is now\", q)\n",
    "print(\"coefficients is now\", coefficients)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To avoid confusion below, let's change the value back:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "coefficients[0] = 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Looking at the end of a list, with negative indices\n",
    "\n",
    "Python allows you to count backwards from the end of a list, by using negative indices:\n",
    "- index -1 refers to the last element\n",
    "- index -k refers to the element k from the end.\n",
    "\n",
    "For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The last digit is 9\n",
      "The third to last digit is 7\n"
     ]
    }
   ],
   "source": [
    "digits = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
    "print('The last digit is', digits[-1])\n",
    "print('The third to last digit is', digits[-3])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This also works with the {ref}`numpy-arrays` and {ref}`tuples` introduced below."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(tuples)=\n",
    "## Tuples\n",
    "\n",
    "One other useful kind of Python collection is a **tuple**, which is a lot like a list except that it is **immutable**: you cannot change individual elements.\n",
    "Tuples are denoted by surrounding the elements with parentheses \"(...)\" in place of the brackets \"[...]\" used with lists:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(2, -10, 8)"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qtuple = (2, -10, 8)\n",
    "qtuple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(2, -10, 8)\n"
     ]
    }
   ],
   "source": [
    "print(qtuple)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "8"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qtuple[2]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Actually, we have seen tuples before without the name being mentioned: when a list of expressions is put on one line separated by commas, the result is a tuple.\n",
    "This is because when creating a tuple, the surrounding parentheses can usually be omitted:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('LeMesurier', 'Brenton')\n"
     ]
    }
   ],
   "source": [
    "name = \"LeMesurier\", \"Brenton\"\n",
    "print(name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tuples can be concatenated by \"addition\", as for lists:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('LeMesurier', 'Brenton', '843-953-5730', 'RSS 344')\n"
     ]
    }
   ],
   "source": [
    "name_and_contact_info = name + ('843-953-5730', 'RSS 344')\n",
    "print(name_and_contact_info)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Naming rules for variables\n",
    "\n",
    "There are some rules limiting which names can be used for variables:\n",
    "- The first character must be a letter.\n",
    "- All characters must be \"alphanumeric\": only letters of digits.\n",
    "- However, the underscore \"_\" (typed with \"shift dash\") is an honorary letter: it can be used where you are tempted to have a space.\n",
    "\n",
    "Note well: no dashes \"-\" or spaces, or any other punctuation.\n",
    "\n",
    "When you are tempted to use a space in a name, such as when the name is a desrciptive phrase, it is recommended to use an underscore. (Another option is to capitalize the first letter of each new word: so-called *camelCase* or *UpperCamelCase*.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise A\n",
    "\n",
    "It will soon be convenient to group the input data to and output values from a calculation in tuples.\n",
    "\n",
    "Do this by rewriting the quadratic solving exercise using a tuple \"coefficients\" containing the coefficients (a, b, c) of a quadratic $ax^2 + bx + c$ and putting the roots into a tuple named \"roots\".\n",
    "\n",
    "Break this up into three steps, each in its own code cell (an organizational pattern that will be important later):\n",
    "1. Input: create the input tuple.\n",
    "2. Calculation: use this tuple to compute the tuple of roots.\n",
    "3. Output: print the roots.\n",
    "\n",
    "This is only a slight variation of what is done above with lists, but the difference will be important later."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(immutability)=\n",
    "## The immutability of tuples (and also of text strings)\n",
    "\n",
    "As mentioned above, a major difference from lists is that tuples are **immutable**; their contents cannot be changed: I cannot change the lead cofficient of the quadratic above with"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'tuple' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "Input \u001b[0;32mIn [25]\u001b[0m, in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m qtuple[\u001b[38;5;241m0\u001b[39m] \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m4\u001b[39m\n",
      "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "qtuple[0] = 4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This difference between **mutable** objects like *lists* and **immutable** ones like *tuples* comes up in multiple places in Python.\n",
    "The one other case that we are most likely to encounter in this course is strings of text, which are in some sense \"tuples of characters\".\n",
    "For example, the characters of a string can be addressed with indices, and concatenated:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The initial letter of 'Python' is 'P'\n",
      "The first three letters are 'Pyt'\n",
      "We are using version 'Python 3'\n"
     ]
    }
   ],
   "source": [
    "language = \"Python\"\n",
    "print(f\"The initial letter of '{language}' is '{language[0]}'\")\n",
    "print(f\"The first three letters are '{language[0:3]}'\")\n",
    "languageversion = language + ' 3'\n",
    "print(f\"We are using version '{languageversion}'\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Aside:** Here a new feature of printing and string manipulation is used, \"f-string formatting\" (new in Python version 3.6). For details, see the notes on\n",
    "[formatted output and some text string manipulation](formatted-output-and-some-text-string-manipulation.ipynb)\n",
    "mentioned above."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Also as with tuples, one cannot change the entries via indexing; we cannot \"lowercase\" that name with"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'str' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "Input \u001b[0;32mIn [27]\u001b[0m, in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m language[\u001b[38;5;241m0\u001b[39m] \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mp\u001b[39m\u001b[38;5;124m\"\u001b[39m\n",
      "\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "language[0] = \"p\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(numpy-arrays)=\n",
    "## Numpy arrays: for vectors, matrices, and beyond\n",
    "\n",
    "Many mathematical calculations involve vectors, matrices and other arrays of numbers.\n",
    "At first glance, Python lists and tuples look like vectors, but as seen above, \"addition\" of such objects does not do what you want with vectors.\n",
    "\n",
    "Thus we need a type of object that is specifically an *array* of numbers of the same type that can be manipulatd like a vector or matrix.\n",
    "There is not a suitable entity for this in the core Python language, but Python has a method to add features using **modules** and **packages**, and the most important one for us is **Numpy**:\n",
    "this provides for suitable numerical arrays through objects of type `ndarray`, and provides tools for working with them, like the function `array()` for creating arrays from lists or tuples.\n",
    "(Numpy also provides a large collection of other tools for numerical computing, as we will see later.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Importing modules\n",
    "\n",
    "One way to make Numpy available is to *import* it with just"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then the function `array` is accessed by its \"fully-qualified name\" `numpy.array`, and we can create an `ndarray` that serves for storing a vector:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "u = numpy.array([1, 2, 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 2, 3])"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "u"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3]\n"
     ]
    }
   ],
   "source": [
    "print(u)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note:** As you might have noticed above, displaying the value of a variable by simply typing its name describes it in more detail than the `print` function; sometimes it is a description that could be used to create the object.\n",
    "Thus I will sometimes use both display methods below, as a reminder of the syntax and semantics of Numpy arrays."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As seen above, if we just want that one function, we can import it specifically with the command"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy import array"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and then it can be referered to by its short name alone:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "v = array([4, 5, 6, 7])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[4 5 6 7]\n"
     ]
    }
   ],
   "source": [
    "print(v)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Notes\n",
    "\n",
    "1. Full disclosure: Python's core collection of resources does provide another kind of object called an *array*,\n",
    "but we will **never** use that in this course, and I advise you to avoid it:\n",
    "the Numpy `ndarray` type of array is far better for what we want to do!\n",
    "The name \"ndarray\" refers to the possibility of creating n-dimensional arrays — for example, to store matrices — which is one of several important advantages.\n",
    "\n",
    "2. There is another add-on package *Pylab*, which contains most of Numpy plus some stuff for graphics (from package *Matplotlib*, which we will meet later, in [Section 8](graphing-with-matplotlib))\n",
    "That is intended to reproduce a Matlab-like environment, especially when used in Spyder, which is deliberately Matlab-like.\n",
    "So you could instead use `from pylab import *`, and that will sometimes be more convenient.\n",
    "However, when you search for documentation, you will find it by searching for `numpy`, not for `pylab`.\n",
    "For example the full name for function `array` is `numpy.array` and once we import Numpy with `import numpy` we can get help on that with the command `help(numpy.array)`.\n",
    "\n",
    "**Beware:** this `help` information is sometimes very lengthy, and \"expert-friendly\" rather than \"beginner-friendly\".  \n",
    "Thus, now is a good time to learn that when the the up-array and down-array keys get to the top or bottom of a cell in a notebook, they keep moving to the previous or next cell, skipping past the output of any code cell. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "help(numpy.array)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The function `help` can also give information about a type of object, such as an `ndarray`.\n",
    "Note that `ndarray` is referred to as a *class*; if that jargon is unfamiliar, you can safely ignore it for now, but if curious you can look at the brief notes on [classes, objects, attributes and methods](classes-objects-attributes-methods)\n",
    "\n",
    "**Beware:** this `help` information is even more long-winded, and tells you far more about numpy arrays than you need to know for now! So make use of that down-arrow key."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "help(numpy.ndarray)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(creating-ndarrays)=\n",
    "### Creating arrays (from lists and otherwise)\n",
    "\n",
    "Numpy arrays (more pedantically, objects of type `ndarray`) are in some ways quite similar to lists, and as seen above, one way to create an array is to convert a list:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "list0 = [1, 2, 3]\n",
    "list1 = [4, 5, 6]\n",
    "array0 = array(list0)\n",
    "array1 = array(list1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3]"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 2, 3])"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "array0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3]\n"
     ]
    }
   ],
   "source": [
    "print(list0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3]\n"
     ]
    }
   ],
   "source": [
    "print(array0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can skip the intermediate step of creating lists and instead create arrays directly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "array0 = array([1, 2, 3])\n",
    "array1 = array([4, 5, 6])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Printing makes these seem very similar, though an array is displayed without commas between elements.\n",
    "Note that this is like the style for a single-row matrix."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "list0 = [1, 2, 3]\n",
      "array0 = [1 2 3]\n"
     ]
    }
   ],
   "source": [
    "print('list0 =', list0)\n",
    "print('array0 =', array0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Also, we can extract and modify elements in the same way:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The first element of list0 is 1\n",
      "The last element of array1 is 6\n",
      "The value of array0  is now [1 7 3]\n"
     ]
    }
   ],
   "source": [
    "print('The first element of list0 is', list0[0])\n",
    "print('The last element of array1 is', array1[-1])\n",
    "array0[1] = 7\n",
    "print('The value of array0  is now', array0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Numpy arrays understand vector arithmetic\n",
    "\n",
    "Addition and other arithmetic reveal some important differences:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5, 6]\n"
     ]
    }
   ],
   "source": [
    "print(list0 + list1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 5 12  9]\n"
     ]
    }
   ],
   "source": [
    "print(array0 + array1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 1, 2, 3]\n"
     ]
    }
   ],
   "source": [
    "print(2 * list0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 2 14  6]\n"
     ]
    }
   ],
   "source": [
    "print(2 * array0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note what multiplication does to lists!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(2Darrays)=\n",
    "### Describing matrices as 2D arrays, or as \"arrays of arrays of numbers\"\n",
    "\n",
    "A list can have other lists as its elements, and likewise an array can be described as having other arrays as its elements, so that a matrix can be described as a succession of rows.\n",
    "First, a list of lists can be created:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "listoflists = [list0, list1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1, 2, 3], [4, 5, 6]]\n"
     ]
    }
   ],
   "source": [
    "print(listoflists)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "listoflists[1][-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then this can be converted to a two dimensional array:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [],
   "source": [
    "matrix = array(listoflists)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2 3]\n",
      " [4 5 6]]\n"
     ]
    }
   ],
   "source": [
    "print(matrix)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 3,  6,  9],\n",
       "       [12, 15, 18]])"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "matrix*3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also combine arrays into new arrays directly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [],
   "source": [
    "anothermatrix = array([array1, array0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[4, 5, 6],\n",
       "       [1, 7, 3]])"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "anothermatrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[4 5 6]\n",
      " [1 7 3]]\n"
     ]
    }
   ],
   "source": [
    "print(anothermatrix)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that we must use the notation <code>array([...])</code> to do this;\n",
    "without the function <code>array()</code> we would get a *list of arrays*, which is a different animal, and much less fun for doing mathematics with:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([4, 5, 6]),\n",
       " array([1, 7, 3]),\n",
       " array([4, 5, 6]),\n",
       " array([1, 7, 3]),\n",
       " array([4, 5, 6]),\n",
       " array([1, 7, 3])]"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "listofarrays = [array1, array0]\n",
    "listofarrays*3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(array-multiple-indexing)=\n",
    "### Referring to array elements with double indices, or with successive single indices\n",
    "\n",
    "The elements of a multi-dimensional array can be referred to with multiple indices:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "matrix[1,2]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "but you can also use a single index to extract an \"element\" that is a row:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([4, 5, 6])"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "matrix[1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and you can use indices successively, to specify first a row and then an element of that row:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "matrix[1][2]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This ability to manipulate rows of a matrix can be useful for linear algebra.\n",
    "For example, in row reduction we might want to subtract four times the first row from the second row, and this is done with:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before the row operation, the matrix is:\n",
      "[[1 2 3]\n",
      " [4 5 6]]\n",
      "After the row operation, it is:\n",
      "[[ 1  2  3]\n",
      " [ 0 -3 -6]]\n"
     ]
    }
   ],
   "source": [
    "print('Before the row operation, the matrix is:')\n",
    "print(matrix)\n",
    "matrix[1] -= 4 * matrix[0]  # Remember, this is short-hand for matrix[1] = matrix[1] - 4 * matrix[0]\n",
    "print('After the row operation, it is:')\n",
    "print(matrix)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note well** the effect of Python indexing starting at zero: the indices used with a vector or matrix are all one less than you might expect based on the notation seen in a linear algebra course."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(higherdimensionarrays)=\n",
    "### Higher dimensional arrays\n",
    "\n",
    "Arrays with three or more indices are possible, though we will not see much of them in this course:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [],
   "source": [
    "arrays_now_in_3D = array([matrix, anothermatrix])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[ 1,  2,  3],\n",
       "        [ 0, -3, -6]],\n",
       "\n",
       "       [[ 4,  5,  6],\n",
       "        [ 1,  7,  3]]])"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arrays_now_in_3D"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[ 1  2  3]\n",
      "  [ 0 -3 -6]]\n",
      "\n",
      " [[ 4  5  6]\n",
      "  [ 1  7  3]]]\n"
     ]
    }
   ],
   "source": [
    "print(arrays_now_in_3D)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Exercise B\n",
    "\n",
    "Create two arrays, containing the matrices\n",
    "$$\n",
    "A = \\left[ \\begin{array}{cc} 2 & 3 \\\\ 1 & 4 \\end{array} \\right], \\qquad B = \\left[ \\begin{array}{cc} 3 & 0 \\\\ 2 & 1 \\end{array} \\right]\n",
    "$$\n",
    "Then look at what is given by the formula\n",
    "\n",
    "    C = A * B\n",
    "and what you get instead with the strange notation\n",
    "\n",
    "    D = A @ B\n",
    "\n",
    "**Explain in words what is going on in each case!**"
   ]
  }
 ],
 "metadata": {
  "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.9.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
