{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "The Python list datatype is (as you might expect) one of the main built-in ways to create a list data structure in Python. Lets review its built-in functions." ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n", "[5, 2, 3]\n", "[1, 2, 3]\n", "[5, 2, 3]\n" ] } ], "source": [ "# Constructor\n", "l1 = [1, 2, 3]\n", "l2 = list( (3, 4, 5) )\n", "l3 = l1+l2\n", "l4 = l1.copy()\n", "l5 = l1\n", "\n", "print(l1 is l4)\n", "print(l1 is l5)\n", "l1[0]=5\n", "print(l1)\n", "print(l4)\n", "print(l5)" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['A', 'B', 'C', 'D']\n" ] } ], "source": [ "# Insert\n", "l1 = []\n", "l1.insert(2, \"A\")\n", "l1.append(\"C\")\n", "l1.insert(1, \"B\")\n", "l1.insert(5, \"D\")\n", "\n", "print(l1)" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 1, 3, 1, 4]\n", "4 [2, 1, 3, 1]\n", "3 [2, 1, 1]\n" ] } ], "source": [ "# Delete\n", "l1 = [1,2,1,3,1,4]\n", "l1.remove(7)\n", "l1.remove(1)\n", "print(l1)\n", "x = l1.pop()\n", "print(x, l1)\n", "y = l1.pop(2)\n", "print(y, l1)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n" ] }, { "ename": "ValueError", "evalue": "5 is not in list", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m/Users/bradsol/Desktop/UIUC/cs277/website/assets/code/sp24/lists.ipynb Cell 5\u001b[0m line \u001b[0;36m5\n\u001b[1;32m 2\u001b[0m l1 \u001b[39m=\u001b[39m [\u001b[39m1\u001b[39m,\u001b[39m2\u001b[39m,\u001b[39m1\u001b[39m,\u001b[39m3\u001b[39m,\u001b[39m1\u001b[39m,\u001b[39m4\u001b[39m]\n\u001b[1;32m 4\u001b[0m \u001b[39mprint\u001b[39m(l1\u001b[39m.\u001b[39mindex(\u001b[39m1\u001b[39m))\n\u001b[0;32m----> 5\u001b[0m \u001b[39mprint\u001b[39m(l1\u001b[39m.\u001b[39;49mindex(\u001b[39m5\u001b[39;49m))\n\u001b[1;32m 6\u001b[0m \u001b[39mprint\u001b[39m(l1\u001b[39m.\u001b[39mindex(\u001b[39m4\u001b[39m))\n\u001b[1;32m 8\u001b[0m \u001b[39mprint\u001b[39m(l1[\u001b[39m0\u001b[39m])\n", "\u001b[0;31mValueError\u001b[0m: 5 is not in list" ] } ], "source": [ "# Index\n", "l1 = [1,2,1,3,1,4]\n", "\n", "print(l1.index(1))\n", "print(l1.index(5))\n", "print(l1.index(4))\n", "\n", "print(l1[0])\n", "print(l1[10])\n", "print(l1[-1])" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n" ] } ], "source": [ "l1 = [1, 2, 1, 3, 1, 4]\n", "\n", "print(len(l1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What will print when we run the following code? Try to work this out by hand before running the code!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def inclass():\n", " l = [1,2,3,4,5,6]\n", " x = l.pop()\n", " l.pop()\n", " l.pop()\n", " l.insert(0, x)\n", " l.append(8)\n", " l += [1, 2]\n", " return l\n", "\n", "print(inclass())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Programming Practice** Complete the code exercise below by writing a function which given a list and a character, returns a list containing the index of every instance of that character." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def indexChar(inList, inChar):\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Bonus Exercise** Now write a function that given a list and an integer, removes the object stored in the list at multiples of the integer. So if my integer was 2, I would remove the 2nd, 4th, 6th, etc... item. If my integer was 3, I would remove the 3rd, 6th, 9th item." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def removeMultiple(inList, num):\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To 'open' a file in Python use the `open()` function. Depending on the arguments, this will either create a readable file object or a writable file object. You cannot both read from and write to a file simultaneously.\n", "\n", "**NOTE:** These examples won't run (because the files they are referencing don't exist.) This is just the code I put on my slides so including them in order. Actual running examples are further below." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "readableFile = open('inputFile.txt', 'r')\n", "\n", "writableFile = open('outputFile.txt', 'w')\n", "\n", "carefulWriteFile = open('outputFile.txt', 'x')\n", "\n", "appendableFile = open('outputFile.txt', 'a')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When you 'open' a file, it is generally good practice to 'close' it. You can either do this manually after you are done or do all your file I/O within a 'with' definition." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Approach 1\n", "\n", "readableFile = open('inputFile.txt', 'r')\n", "\n", "fileData = readableFile.read()\n", "\n", "readableFile.close()\n", "\n", "\n", "# Approach 2\n", "with open('inputFile.txt', 'r') as myFile:\n", " fileData = myFile.read()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Example code blocks involving reading / writing files won't work unless you have the files locally. Accordingly I've provided the *write* examples before the *read* examples so you can generate your own files.\n", "\n", "**NOTE:** The functions will create (or attempt to create) a 'data' folder to store the written files. Feel free to comment those lines out and adjust the file paths as needed if your permissions are set to not allow this." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Write Examples:**\n", "\n", "There are two key ways to 'write' a file -- `write (w)` and `append (a)`. Write will overwrite the file if it exists (so be careful!) while append will write anything you add to the end of the file. They are both dangerous in different ways." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "if not os.path.exists('data'):\n", " os.mkdir(\"data\")\n", "\n", "with open('data/temp1.txt', 'w') as myFile:\n", " for i in range(10):\n", " myFile.write(str(i))\n", " myFile.write(\"\\n\")\n", " myFile.write(\"Line 2\")\n", "\n", "myFile = open('data/temp2.txt', 'w')\n", "for i in range(5):\n", " myFile.write(str(i) + \"\\n\")\n", "myFile.close()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('data/temp2.txt', 'a') as myFile:\n", " myFile.write(\"Hello World!\\n\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Read Examples:** \n", "\n", "`readlines()`, `read()` and `readline()` each parse a different 'amount' of the input file. When might you prefer one over the other?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('data/temp1.txt') as myFile:\n", " inList = myFile.readlines()\n", "print(inList)\n", "\n", "myFile = open('data/temp2.txt')\n", "for i in range(10):\n", " print(\"Line Content: {}\".format(myFile.readline()))\n", "myFile.close()\n", "\n", "with open('data/temp1.txt') as myFile:\n", " print(myFile.read())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "myFile = open('data/temp2.txt')\n", "for i in range(6):\n", " print(\"Line Content: {}\".format(myFile.readline().strip()))\n", "myFile.close()\n", "\n", "with open('data/temp2.txt') as myFile:\n", " for line in myFile:\n", " print(line.strip())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('data/temp1.txt') as myFile:\n", " text = myFile.read()\n", " print(\"'{}'\".format(text))\n", " print(text.split())\n", "\n", " print(text.split(\"5\"))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Programming Practice:** Write a function that given an input file and a filename, writes a new file that contains all the same lines in reversed order." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Randomness in Python** Python's coding simplicity and data science foundations makes it a great tool for creating simple random datasets. One such Python module is `random`, which implements pseudo-random number generators according to various probability distributions. What does it mean to be pseudo-random? Lets explore below!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import random\n", "for i in range(3):\n", " print(random.random())\n", "\n", "for i in range(2):\n", " random.seed(1)\n", " for j in range(3):\n", " print(random.random())\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "l = []\n", "for i in range(10):\n", " l.append(random.randint(0, 10))\n", "\n", "print(l)\n", "print(random.choice(l))\n", "print(random.sample(list(range(10)), 5))\n", "\n", "random.shuffle(l)\n", "print(l)\n", "random.shuffle(l)\n", "print(l)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Write a function that takes in two numbers, a length and count, and generates count random variables across length. Instead of storing the sequence, we will only store the counts assigned to each value. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def buckets(len, count):\n", " pass" ] } ], "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.11.1" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "1a1af0ee75eeea9e2e1ee996c87e7a2b11a0bebd85af04bb136d915cefc0abce" } } }, "nbformat": 4, "nbformat_minor": 2 }