{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 4: Lists and tuples\n",
    "\n",
    "Asiman Data School, Module 1: Foundations of Python Programming. Week 2, Thursday.\n",
    "\n",
    "This notebook follows the lesson page. Read the text, run the cell under it with Shift + Enter, then change the values in the cell and run it again. Seeing the output change is how the rules become clear.\n",
    "\n",
    "Run the cells from top to bottom. When a cell reads input, a small box appears: type the values there and press Enter. The practice problems are in a separate notebook, topic-04-practice.ipynb.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. Reading several values in one line with map\n",
    "2. Lists: creating, reading and changing\n",
    "3. Adding and removing items\n",
    "4. Searching, ordering, copying and operators\n",
    "5. Going through a list with loops and if/else\n",
    "6. Input, text, nested lists and functions\n",
    "7. Tuples\n",
    "8. map and filter\n",
    "9. Common mistakes\n",
    "10. Solved problems (easy to medium-hard)\n",
    "11. Practice problems (try them yourself) (in topic-04-practice.ipynb)\n",
    "12. Check yourself (on the website)\n",
    "13. Quick summary"
   ],
   "id": "t04-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: lists and tuples\n",
    "\n",
    "What matters most in this lesson. Five things matter most today: reading values with `a, b = map(int, input().split())` and a whole list with `list(map(int, input().split()))`; creating a list and reading it with indexes and slices; the everyday methods `append`, `insert`, `remove`, `pop` and `sort`; going through a list with `for` and `if`; and the difference between a list (it can change) and a tuple (it cannot).\n",
    "\n",
    "`map` and `filter` with `lambda` come at the end. Take them slowly: every `map` and every `filter` in this lesson is also shown as a normal loop, and the loop is always a correct answer. There are 26 solved problems. You do not need all of them today: start with Level 1 and come back for the rest.\n",
    "\n",
    "A beginner-friendly guide to the first two data structures of Python: lists and tuples. It starts from the simplest examples and gets harder step by step. It shows every everyday method (`append`, `extend`, `insert`, `remove`, `pop`, `del`, `sort` and more), how to use operators, `if/else`, `for` and `while` with lists and tuples, how to read a whole list from the user in one line with `map`, and how `map` and `filter` work and differ. Then it walks through 26 solved problems from easy to medium-hard. At the end there are practice problems.\n",
    "\n",
    "You should already know variables, data types, operators, `if/else`, loops and functions.\n",
    "\n",
    "## 1. Reading several values in one line with `map`\n",
    "\n",
    "Until now we read one value per line:\n",
    "\n",
    "When the cell asks for input, type `5`, then `7`."
   ],
   "id": "t04-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "5",
      "7"
     ]
    }
   },
   "outputs": [],
   "source": [
    "a = int(input())\n",
    "b = int(input())\n",
    "print(a + b)"
   ],
   "id": "t04-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The user had to press Enter after each number. Very often the numbers come on one line, separated by spaces, like `5 7`. To read them we need three small steps. Let us look at each step alone.\n",
    "\n",
    "### 1.1 Step 1: `input()` gives one text\n",
    "\n",
    "Change it and run: type three numbers in the input box. `type(line)` is still `str`.\n",
    "\n",
    "When the cell asks for input, type `5 7`."
   ],
   "id": "t04-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "5 7"
     ]
    }
   },
   "outputs": [],
   "source": [
    "line = input()\n",
    "print(line)\n",
    "print(type(line))"
   ],
   "id": "t04-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`input()` always gives text. Here the text is `\"5 7\"`: one string, not two numbers.\n",
    "\n",
    "### 1.2 Step 2: `.split()` cuts the text into pieces\n",
    "\n",
    "Change it and run: put three numbers in the text: `\"5 7 9\"`. How many pieces are there now?"
   ],
   "id": "t04-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "line = \"5 7\"\n",
    "parts = line.split()\n",
    "print(parts)"
   ],
   "id": "t04-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`.split()` cuts the text at the spaces and gives the pieces back in square brackets. This is a list (the main topic of this lesson). Notice the quotes: the pieces are still text, `'5'` and `'7'`.\n",
    "\n",
    "### 1.3 Step 3: `map(int, ...)` converts every piece\n",
    "\n",
    "We need to run `int()` on every piece. That is exactly what `map` does:\n",
    "\n",
    "```\n",
    "map(function, sequence)\n",
    "```\n",
    "\n",
    "`map` takes a function and a sequence, and applies the function to every item of the sequence.\n",
    "\n",
    "Change it and run: change `int` to `float`. What do `a` and `b` look like now?"
   ],
   "id": "t04-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "parts = [\"5\", \"7\"]\n",
    "numbers = map(int, parts)\n",
    "a, b = numbers\n",
    "print(a, b)\n",
    "print(a + b)"
   ],
   "id": "t04-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`map(int, parts)` means: \"run `int` on `'5'`, then run `int` on `'7'`\". The line `a, b = numbers` puts the first result into `a` and the second into `b`.\n",
    "\n",
    "Notice: we write `int`, not `int()`. We give `map` the function itself. `map` is the one that calls it, once for every item.\n",
    "\n",
    "### 1.4 All three steps in one line\n",
    "\n",
    "Change it and run: type `10 25` in the input box. Then type only one number and read the error.\n",
    "\n",
    "When the cell asks for input, type `5 7`."
   ],
   "id": "t04-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "5 7"
     ]
    }
   },
   "outputs": [],
   "source": [
    "a, b = map(int, input().split())\n",
    "print(a + b)"
   ],
   "id": "t04-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Read it from the inside out:\n",
    "\n",
    "| Piece | What it does | Result for the input `5 7` |\n",
    "| --- | --- | --- |\n",
    "| `input()` | reads the line as text | `\"5 7\"` |\n",
    "| `.split()` | cuts the text at the spaces | `['5', '7']` |\n",
    "| `map(int, ...)` | runs `int` on every piece | `5` and `7` |\n",
    "| `a, b = ...` | stores the results in two variables | `a` is 5, `b` is 7 |\n",
    "\n",
    "### 1.5 The same idea with other types and more values\n",
    "\n",
    "When the cell asks for input, type `3 10 4`."
   ],
   "id": "t04-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "3 10 4"
     ]
    }
   },
   "outputs": [],
   "source": [
    "a, b, c = map(int, input().split())\n",
    "print(a + b + c)"
   ],
   "id": "t04-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Change it and run: type `3 4`. The result is still a decimal number, because of `float`.\n",
    "\n",
    "When the cell asks for input, type `2.5 4`."
   ],
   "id": "t04-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "2.5 4"
     ]
    }
   },
   "outputs": [],
   "source": [
    "width, height = map(float, input().split())\n",
    "print(width * height)"
   ],
   "id": "t04-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For text you do not need `map`, because `.split()` already gives text:\n",
    "\n",
    "When the cell asks for input, type `Aylin Demir`."
   ],
   "id": "t04-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "Aylin Demir"
     ]
    }
   },
   "outputs": [],
   "source": [
    "first_name, last_name = input().split()\n",
    "print(\"Hello,\", first_name, last_name)"
   ],
   "id": "t04-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.6 The number of variables must match\n",
    "\n",
    "If the user types 3 values but you wrote 2 variables, Python stops with an error:\n",
    "\n",
    "```python\n",
    "a, b = map(int, input().split())\n",
    "```\n",
    "\n",
    "```\n",
    "5 7 9\n",
    "ValueError: too many values to unpack (expected 2)\n",
    "```\n",
    "\n",
    "And with too few values:\n",
    "\n",
    "```python\n",
    "a, b = map(int, input().split())\n",
    "```\n",
    "\n",
    "```\n",
    "5\n",
    "ValueError: not enough values to unpack (expected 2, got 1)\n",
    "```\n",
    "\n",
    "What if we do not know how many numbers the user will type? Then we cannot write a variable for each one. We need one variable that holds many values. That is a list. We come back to `map` in Part 6 (reading a whole list) and in Part 8 (`map` in detail).\n",
    "\n",
    "## 2. Lists: creating, reading and changing\n",
    "\n",
    "### 2.1 What is a list?\n",
    "\n",
    "Imagine you must store the grades of 5 students. Without a list:\n",
    "\n",
    "```python\n",
    "grade1 = 85\n",
    "grade2 = 92\n",
    "grade3 = 78\n",
    "grade4 = 60\n",
    "grade5 = 95\n",
    "```\n",
    "\n",
    "Now imagine 500 students. A list stores many values in one variable, in order:"
   ],
   "id": "t04-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = [85, 92, 78, 60, 95]\n",
    "print(grades)"
   ],
   "id": "t04-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Real-life picture: a list is a row of numbered boxes, or a shopping list where you can add items, cross items out, and change them.\n",
    "\n",
    "### 2.2 Creating lists\n",
    "\n",
    "A list is written in square brackets, with commas between the items:\n",
    "\n",
    "Change it and run: add one more name to `names`."
   ],
   "id": "t04-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [10, 20, 30]\n",
    "names = [\"Aylin\", \"Murad\", \"Leyla\"]\n",
    "prices = [2.5, 10.0, 7.25]\n",
    "empty = []\n",
    "mixed = [1, \"two\", 3.0, True]\n",
    "\n",
    "print(numbers)\n",
    "print(names)\n",
    "print(prices)\n",
    "print(empty)\n",
    "print(mixed)\n",
    "print(type(numbers))"
   ],
   "id": "t04-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- A list can hold any type, even different types together (but usually all items have the same type).\n",
    "- A list can be empty: `[]`.\n",
    "- The same value can appear more than once: `[1, 1, 2]`.\n",
    "\n",
    "### 2.3 How many items? `len()`\n",
    "\n",
    "Change it and run: add a grade to the list. `len` grows by one."
   ],
   "id": "t04-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = [85, 92, 78, 60, 95]\n",
    "print(len(grades))\n",
    "print(len([]))"
   ],
   "id": "t04-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4 Making a list from something else: `list()`\n",
    "\n",
    "Change it and run: change `\"Python\"` to your name."
   ],
   "id": "t04-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(list(\"Python\"))\n",
    "print(list(range(5)))\n",
    "print(list(range(1, 11, 2)))"
   ],
   "id": "t04-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`list()` turns a text into a list of characters, and a `range` into a list of numbers.\n",
    "\n",
    "### 2.5 Indexes\n",
    "\n",
    "Every item has a position number called an index. Counting starts at 0.\n",
    "\n",
    "```\n",
    "items:     [\"a\", \"b\", \"c\", \"d\", \"e\"]\n",
    "index:       0    1    2    3    4\n",
    "negative:   -5   -4   -3   -2   -1\n",
    "```\n",
    "\n",
    "Change it and run: print `letters[2]`."
   ],
   "id": "t04-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "letters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n",
    "print(letters[0])\n",
    "print(letters[1])\n",
    "print(letters[4])"
   ],
   "id": "t04-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Negative indexes count from the end. `-1` is the last item:\n",
    "\n",
    "Change it and run: print `letters[-5]`. Which item is it?"
   ],
   "id": "t04-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "letters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n",
    "print(letters[-1])\n",
    "print(letters[-2])"
   ],
   "id": "t04-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last item is always `letters[-1]` or `letters[len(letters) - 1]`.\n",
    "\n",
    "An index that does not exist gives an error:\n",
    "\n",
    "```python\n",
    "letters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n",
    "print(letters[5])\n",
    "```\n",
    "\n",
    "```\n",
    "IndexError: list index out of range\n",
    "```\n",
    "\n",
    "### 2.6 Slices: taking a part of a list\n",
    "\n",
    "`list[start:stop]` gives a new list from index `start` up to, but not including, `stop` (the same rule as `range`).\n",
    "\n",
    "Change it and run: print `numbers[2:5]`. Predict the result first."
   ],
   "id": "t04-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [10, 20, 30, 40, 50, 60]\n",
    "print(numbers[1:4])\n",
    "print(numbers[:3])\n",
    "print(numbers[3:])\n",
    "print(numbers[-2:])\n",
    "print(numbers[:])"
   ],
   "id": "t04-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Slice | Meaning |\n",
    "| --- | --- |\n",
    "| `numbers[1:4]` | indexes 1, 2, 3 |\n",
    "| `numbers[:3]` | the first 3 items |\n",
    "| `numbers[3:]` | from index 3 to the end |\n",
    "| `numbers[-2:]` | the last 2 items |\n",
    "| `numbers[:]` | the whole list (a copy) |\n",
    "\n",
    "A third number is the step:\n",
    "\n",
    "Change it and run: print `numbers[::3]`."
   ],
   "id": "t04-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [10, 20, 30, 40, 50, 60]\n",
    "print(numbers[::2])\n",
    "print(numbers[1::2])\n",
    "print(numbers[::-1])"
   ],
   "id": "t04-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`numbers[::-1]` gives the list reversed.\n",
    "\n",
    "Slices never give an error, even when the numbers are too big:"
   ],
   "id": "t04-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [10, 20, 30]\n",
    "print(numbers[1:100])\n",
    "print(numbers[5:])"
   ],
   "id": "t04-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.7 Lists can be changed (they are mutable)\n",
    "\n",
    "A text cannot be changed in place, but a list can. This is the most important property of a list. The word for it is mutable (changeable).\n",
    "\n",
    "Change it and run: change the second grade to 100."
   ],
   "id": "t04-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = [85, 92, 78]\n",
    "grades[0] = 90\n",
    "print(grades)\n",
    "grades[-1] = grades[-1] + 5\n",
    "print(grades)"
   ],
   "id": "t04-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can even replace a whole slice:\n",
    "\n",
    "Change it and run: replace the slice with three items: `[20, 30, 40]`. The list gets longer."
   ],
   "id": "t04-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5]\n",
    "numbers[1:3] = [20, 30]\n",
    "print(numbers)"
   ],
   "id": "t04-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compare with text, which cannot be changed like this:\n",
    "\n",
    "```python\n",
    "word = \"cat\"\n",
    "word[0] = \"b\"\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: 'str' object does not support item assignment\n",
    "```\n",
    "\n",
    "Changing an index that does not exist is also an error. You cannot add a new item this way:\n",
    "\n",
    "```python\n",
    "grades = [85, 92, 78]\n",
    "grades[3] = 100\n",
    "```\n",
    "\n",
    "```\n",
    "IndexError: list assignment index out of range\n",
    "```\n",
    "\n",
    "To add items we use methods. A method is a function that belongs to a value, and is called with a dot: `list_name.method()`.\n",
    "\n",
    "## 3. Adding and removing items\n",
    "\n",
    "### 3.1 `append(item)`: add one item at the end\n",
    "\n",
    "Change it and run: append your favourite fruit."
   ],
   "id": "t04-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\"]\n",
    "fruits.append(\"cherry\")\n",
    "print(fruits)\n",
    "fruits.append(\"orange\")\n",
    "print(fruits)"
   ],
   "id": "t04-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`append` is the most used list method. A very common pattern is to start with an empty list and fill it in a loop:\n",
    "\n",
    "Change it and run: change `number * number` to `number * 2`."
   ],
   "id": "t04-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "squares = []\n",
    "for number in range(1, 6):\n",
    "    squares.append(number * number)\n",
    "print(squares)"
   ],
   "id": "t04-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 `insert(index, item)`: add one item at a position\n",
    "\n",
    "Change it and run: insert `\"pear\"` at index 2."
   ],
   "id": "t04-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "fruits.insert(1, \"kiwi\")\n",
    "print(fruits)\n",
    "fruits.insert(0, \"mango\")\n",
    "print(fruits)"
   ],
   "id": "t04-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The new item takes the given index, and everything after it moves one place to the right.\n",
    "\n",
    "### 3.3 `extend(other_list)`: add all items of another list"
   ],
   "id": "t04-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\"]\n",
    "fruits.extend([\"cherry\", \"orange\"])\n",
    "print(fruits)"
   ],
   "id": "t04-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.4 `append` vs `extend` (a classic confusion)\n",
    "\n",
    "Change it and run: print `a[2]` and `b[2]`."
   ],
   "id": "t04-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [1, 2]\n",
    "a.append([3, 4])\n",
    "print(a)\n",
    "print(len(a))\n",
    "\n",
    "b = [1, 2]\n",
    "b.extend([3, 4])\n",
    "print(b)\n",
    "print(len(b))"
   ],
   "id": "t04-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `append` adds its argument as one item (here a list inside the list).\n",
    "- `extend` adds each item of its argument.\n",
    "\n",
    "### 3.5 Joining with `+`\n",
    "\n",
    "`+` builds a new list and leaves the originals unchanged:\n",
    "\n",
    "Change it and run: print `second + first`. The order changes."
   ],
   "id": "t04-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "first = [1, 2]\n",
    "second = [3, 4]\n",
    "both = first + second\n",
    "print(both)\n",
    "print(first)"
   ],
   "id": "t04-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Way | What it adds | Changes the list itself? |\n",
    "| --- | --- | --- |\n",
    "| `a.append(x)` | one item at the end | yes |\n",
    "| `a.insert(i, x)` | one item at index `i` | yes |\n",
    "| `a.extend(b)` | every item of `b` at the end | yes |\n",
    "| `a + b` | every item of `b` | no, makes a new list |\n",
    "\n",
    "### 3.6 `remove(value)`: remove by value\n",
    "\n",
    "Change it and run: add a second `fruits.remove(\"banana\")` line. Then a third one, and read the error."
   ],
   "id": "t04-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\", \"banana\"]\n",
    "fruits.remove(\"banana\")\n",
    "print(fruits)"
   ],
   "id": "t04-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Only the first matching item is removed. If the value is not in the list, Python stops with an error:\n",
    "\n",
    "```python\n",
    "fruits = [\"apple\", \"banana\"]\n",
    "fruits.remove(\"kiwi\")\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: list.remove(x): x not in list\n",
    "```\n",
    "\n",
    "The safe way is to check first:\n",
    "\n",
    "Change it and run: change `\"kiwi\"` to `\"apple\"` in all three places."
   ],
   "id": "t04-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\"]\n",
    "if \"kiwi\" in fruits:\n",
    "    fruits.remove(\"kiwi\")\n",
    "else:\n",
    "    print(\"kiwi is not in the list\")"
   ],
   "id": "t04-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.7 `pop()`: remove by position and give the item back"
   ],
   "id": "t04-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "last = fruits.pop()\n",
    "print(last)\n",
    "print(fruits)\n",
    "\n",
    "first = fruits.pop(0)\n",
    "print(first)\n",
    "print(fruits)"
   ],
   "id": "t04-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `pop()` without a number removes the last item.\n",
    "- `pop(index)` removes the item at that index.\n",
    "- In both cases the removed item is returned, so you can store and use it.\n",
    "\n",
    "`pop` on an empty list is an error:\n",
    "\n",
    "```python\n",
    "empty = []\n",
    "empty.pop()\n",
    "```\n",
    "\n",
    "```\n",
    "IndexError: pop from empty list\n",
    "```\n",
    "\n",
    "### 3.8 `del`: delete by index or by slice\n",
    "\n",
    "Change it and run: delete the last item with `del numbers[-1]`."
   ],
   "id": "t04-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [10, 20, 30, 40, 50]\n",
    "del numbers[0]\n",
    "print(numbers)\n",
    "del numbers[1:3]\n",
    "print(numbers)"
   ],
   "id": "t04-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`del` is a statement, not a method. It does not give the item back.\n",
    "\n",
    "### 3.9 `clear()`: remove everything"
   ],
   "id": "t04-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [10, 20, 30]\n",
    "numbers.clear()\n",
    "print(numbers)\n",
    "print(len(numbers))"
   ],
   "id": "t04-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.10 Which one should I use?\n",
    "\n",
    "| Tool | Removes by | Gives the item back? | Example |\n",
    "| --- | --- | --- | --- |\n",
    "| `remove(value)` | value (first match) | no | `fruits.remove(\"banana\")` |\n",
    "| `pop()` | last position | yes | `last = fruits.pop()` |\n",
    "| `pop(index)` | index | yes | `first = fruits.pop(0)` |\n",
    "| `del list[index]` | index or slice | no | `del numbers[1:3]` |\n",
    "| `clear()` | everything | no | `numbers.clear()` |\n",
    "\n",
    "## 4. Searching, ordering, copying and operators\n",
    "\n",
    "### 4.1 Is it in the list? `in` and `not in`"
   ],
   "id": "t04-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "print(\"banana\" in fruits)\n",
    "print(\"kiwi\" in fruits)\n",
    "print(\"kiwi\" not in fruits)"
   ],
   "id": "t04-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.2 Where is it? `index(value)`\n",
    "\n",
    "Change it and run: ask for the index of `\"apple\"`."
   ],
   "id": "t04-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\", \"banana\"]\n",
    "print(fruits.index(\"banana\"))\n",
    "print(fruits.index(\"cherry\"))"
   ],
   "id": "t04-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`index` gives the position of the first match. A missing value is an error, so check with `in` first:\n",
    "\n",
    "```python\n",
    "fruits = [\"apple\", \"banana\"]\n",
    "print(fruits.index(\"kiwi\"))\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: list.index(x): x not in list\n",
    "```\n",
    "\n",
    "### 4.3 How many times? `count(value)`\n",
    "\n",
    "Change it and run: count `\"no\"`."
   ],
   "id": "t04-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "votes = [\"yes\", \"no\", \"yes\", \"yes\", \"no\"]\n",
    "print(votes.count(\"yes\"))\n",
    "print(votes.count(\"maybe\"))"
   ],
   "id": "t04-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.4 Built-in functions for lists: `len`, `sum`, `min`, `max`\n",
    "\n",
    "Change it and run: add the grade 0 to the list. Which results change?"
   ],
   "id": "t04-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = [85, 92, 78, 60, 95]\n",
    "print(len(grades))\n",
    "print(sum(grades))\n",
    "print(min(grades))\n",
    "print(max(grades))\n",
    "print(sum(grades) / len(grades))"
   ],
   "id": "t04-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`sum(grades) / len(grades)` is the average. `min` and `max` also work with text (alphabetical order):"
   ],
   "id": "t04-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "names = [\"Murad\", \"Aylin\", \"Leyla\"]\n",
    "print(min(names))\n",
    "print(max(names))"
   ],
   "id": "t04-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.5 `sort()`: sort the list itself"
   ],
   "id": "t04-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [40, 10, 30, 20]\n",
    "numbers.sort()\n",
    "print(numbers)\n",
    "\n",
    "numbers.sort(reverse=True)\n",
    "print(numbers)"
   ],
   "id": "t04-072"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "names = [\"Murad\", \"Aylin\", \"Leyla\"]\n",
    "names.sort()\n",
    "print(names)"
   ],
   "id": "t04-073"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.6 `sorted()`: make a new sorted list\n",
    "\n",
    "Change it and run: use `sorted(numbers, reverse=True)`."
   ],
   "id": "t04-074"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [40, 10, 30, 20]\n",
    "ordered = sorted(numbers)\n",
    "print(ordered)\n",
    "print(numbers)"
   ],
   "id": "t04-075"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The original list stays as it was.\n",
    "\n",
    "|  | `list.sort()` | `sorted(list)` |\n",
    "| --- | --- | --- |\n",
    "| Kind | a method | a built-in function |\n",
    "| Changes the original? | yes | no |\n",
    "| Gives back | `None` | a new sorted list |\n",
    "| Use it when | you no longer need the old order | you want to keep the original |\n",
    "\n",
    "### 4.7 A very common mistake\n",
    "\n",
    "`sort()` changes the list and returns `None`. So this loses your list:\n",
    "\n",
    "Change it and run: fix it in both ways."
   ],
   "id": "t04-076"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [40, 10, 30, 20]\n",
    "numbers = numbers.sort()\n",
    "print(numbers)"
   ],
   "id": "t04-077"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Write `numbers.sort()` alone on its line, or `numbers = sorted(numbers)`.\n",
    "\n",
    "### 4.8 Sorting by a rule: `key`\n",
    "\n",
    "`key` is a function that decides what to compare. Here words are sorted by their length:\n",
    "\n",
    "Change it and run: sort the same words without `key`. The order becomes alphabetical."
   ],
   "id": "t04-078"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "words = [\"banana\", \"kiwi\", \"apple\", \"fig\"]\n",
    "words.sort(key=len)\n",
    "print(words)"
   ],
   "id": "t04-079"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The rule can also be a lambda (from the last lesson). Here the words are sorted by their last letter, and `max` finds the longest word:\n",
    "\n",
    "Change it and run: sort by the second letter: `word[1]`."
   ],
   "id": "t04-080"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "words = [\"banana\", \"kiwi\", \"apple\", \"fig\"]\n",
    "print(sorted(words, key=lambda word: word[-1]))\n",
    "print(max(words, key=len))"
   ],
   "id": "t04-081"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.9 `reverse()` and `[::-1]`"
   ],
   "id": "t04-082"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4]\n",
    "numbers.reverse()\n",
    "print(numbers)\n",
    "\n",
    "letters = [\"a\", \"b\", \"c\"]\n",
    "print(letters[::-1])\n",
    "print(letters)"
   ],
   "id": "t04-083"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`reverse()` changes the list itself and does not sort it: it only turns the order around. `[::-1]` makes a new reversed list.\n",
    "\n",
    "### 4.10 Text and numbers cannot be sorted together\n",
    "\n",
    "```python\n",
    "mixed = [3, \"apple\", 1]\n",
    "mixed.sort()\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: '<' not supported between instances of 'str' and 'int'\n",
    "```\n",
    "\n",
    "### 4.11 Copying a list (an important trap)\n",
    "\n",
    "Change it and run: append to `a` instead of `b`. Both still change."
   ],
   "id": "t04-084"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [1, 2, 3]\n",
    "b = a\n",
    "b.append(4)\n",
    "print(a)\n",
    "print(b)"
   ],
   "id": "t04-085"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We changed `b`, but `a` changed too. Why? `b = a` does not copy the list. It gives the same list a second name. There is only one list in memory.\n",
    "\n",
    "To get a real, separate copy, use `.copy()`:"
   ],
   "id": "t04-086"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [1, 2, 3]\n",
    "b = a.copy()\n",
    "b.append(4)\n",
    "print(a)\n",
    "print(b)"
   ],
   "id": "t04-087"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Three ways make a copy, and all give the same result:"
   ],
   "id": "t04-088"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [1, 2, 3]\n",
    "copy1 = a.copy()\n",
    "copy2 = a[:]\n",
    "copy3 = list(a)\n",
    "print(copy1, copy2, copy3)"
   ],
   "id": "t04-089"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`==` checks whether two lists have the same items. `is` checks whether they are the same list in memory:"
   ],
   "id": "t04-090"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [1, 2, 3]\n",
    "b = a\n",
    "c = a.copy()\n",
    "print(a == c)\n",
    "print(a is b)\n",
    "print(a is c)"
   ],
   "id": "t04-091"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.12 All list methods in one table\n",
    "\n",
    "| Method | What it does | Changes the list? | Gives back |\n",
    "| --- | --- | --- | --- |\n",
    "| `append(x)` | adds `x` at the end | yes | `None` |\n",
    "| `insert(i, x)` | adds `x` at index `i` | yes | `None` |\n",
    "| `extend(other)` | adds every item of `other` | yes | `None` |\n",
    "| `remove(x)` | removes the first `x` | yes | `None` |\n",
    "| `pop()` | removes the last item | yes | the removed item |\n",
    "| `pop(i)` | removes the item at index `i` | yes | the removed item |\n",
    "| `clear()` | removes all items | yes | `None` |\n",
    "| `index(x)` | finds the position of the first `x` | no | the index |\n",
    "| `count(x)` | counts how many times `x` appears | no | a number |\n",
    "| `sort()` | sorts the list | yes | `None` |\n",
    "| `reverse()` | turns the order around | yes | `None` |\n",
    "| `copy()` | makes a separate copy | no | a new list |\n",
    "\n",
    "Built-in functions that take a list: `len(a)`, `sum(a)`, `min(a)`, `max(a)`, `sorted(a)`, `list(a)`.\n",
    "\n",
    "Remember: the methods that change the list (`append`, `sort`, `reverse`, ...) return `None`. Do not write `a = a.append(5)`.\n",
    "\n",
    "### 4.13 Operators with lists\n",
    "\n",
    "| Operator | Meaning | Example | Result |\n",
    "| --- | --- | --- | --- |\n",
    "| `+` | join two lists | `[1, 2] + [3]` | `[1, 2, 3]` |\n",
    "| `*` | repeat a list | `[0] * 4` | `[0, 0, 0, 0]` |\n",
    "| `in` | is the value inside? | `2 in [1, 2, 3]` | `True` |\n",
    "| `not in` | is the value missing? | `5 not in [1, 2, 3]` | `True` |\n",
    "| `==` | same items in the same order? | `[1, 2] == [1, 2]` | `True` |\n",
    "| `!=` | different? | `[1, 2] != [2, 1]` | `True` |\n",
    "| `<`, `>` | compare item by item | `[1, 2] < [1, 3]` | `True` |\n",
    "\n",
    "Change it and run: print `[1, 2] * 2 + [3]`."
   ],
   "id": "t04-092"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print([1, 2] + [3])\n",
    "print([0] * 4)\n",
    "print([\"ha\"] * 3)\n",
    "print([1, 2] == [1, 2])\n",
    "print([1, 2] == [2, 1])\n",
    "print([1, 2] < [1, 3])"
   ],
   "id": "t04-093"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Order matters: `[1, 2]` and `[2, 1]` are different lists.\n",
    "\n",
    "`+=` adds the items of another list (it works like `extend`):"
   ],
   "id": "t04-094"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2]\n",
    "numbers += [3, 4]\n",
    "print(numbers)"
   ],
   "id": "t04-095"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A list and a single number cannot be added:\n",
    "\n",
    "```python\n",
    "numbers = [1, 2]\n",
    "numbers = numbers + 3\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: can only concatenate list (not \"int\") to list\n",
    "```\n",
    "\n",
    "Write `numbers + [3]` or `numbers.append(3)`.\n",
    "\n",
    "## 5. Going through a list with loops and `if/else`\n",
    "\n",
    "This is where lists become powerful: one loop can process 5 items or 5 million.\n",
    "\n",
    "### 5.1 `for item in list` (the simplest way)\n",
    "\n",
    "Change it and run: add a fourth fruit to the list. The loop needs no change."
   ],
   "id": "t04-096"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "for fruit in fruits:\n",
    "    print(fruit)"
   ],
   "id": "t04-097"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The loop variable takes each item in turn. Use this when you only need the values.\n",
    "\n",
    "### 5.2 `for i in range(len(list))` (when you need the index)"
   ],
   "id": "t04-098"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "for i in range(len(fruits)):\n",
    "    print(i, fruits[i])"
   ],
   "id": "t04-099"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.3 `enumerate` (index and item together)"
   ],
   "id": "t04-100"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "for i, fruit in enumerate(fruits):\n",
    "    print(i, fruit)"
   ],
   "id": "t04-101"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Start counting at 1 with `enumerate(fruits, 1)`:\n",
    "\n",
    "Change it and run: start the numbering at 10."
   ],
   "id": "t04-102"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "for number, fruit in enumerate(fruits, 1):\n",
    "    print(number, fruit)"
   ],
   "id": "t04-103"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.4 `while` with a list"
   ],
   "id": "t04-104"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "i = 0\n",
    "while i < len(fruits):\n",
    "    print(fruits[i])\n",
    "    i = i + 1"
   ],
   "id": "t04-105"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Way | You get | Use it when |\n",
    "| --- | --- | --- |\n",
    "| `for item in items:` | each item | you only read the values (most common) |\n",
    "| `for i in range(len(items)):` | each index | you need positions, or you change items |\n",
    "| `for i, item in enumerate(items):` | index and item | you need both |\n",
    "| `while i < len(items):` | each index | you may stop early or move in special steps |\n",
    "\n",
    "### 5.5 Loop + `if`: the sum of the odd numbers\n",
    "\n",
    "Change it and run: change the condition to `number % 2 == 0` to add the even numbers."
   ],
   "id": "t04-106"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 8, 5, 12, 7, 10]\n",
    "total = 0\n",
    "for number in numbers:\n",
    "    if number % 2 == 1:\n",
    "        total = total + number\n",
    "print(\"Sum of odd numbers:\", total)"
   ],
   "id": "t04-107"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Trace table:\n",
    "\n",
    "| `number` | odd? | `total` |\n",
    "| --- | --- | --- |\n",
    "| 3 | yes | 3 |\n",
    "| 8 | no | 3 |\n",
    "| 5 | yes | 8 |\n",
    "| 12 | no | 8 |\n",
    "| 7 | yes | 15 |\n",
    "| 10 | no | 15 |\n",
    "\n",
    "### 5.6 Loop + `if`: counting\n",
    "\n",
    "Change it and run: change the pass mark from 50 to 80."
   ],
   "id": "t04-108"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = [85, 42, 78, 60, 95, 30]\n",
    "passed = 0\n",
    "for grade in grades:\n",
    "    if grade >= 50:\n",
    "        passed = passed + 1\n",
    "print(\"Passed:\", passed)\n",
    "print(\"Failed:\", len(grades) - passed)"
   ],
   "id": "t04-109"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.7 Loop + `if/else`: a label for every item"
   ],
   "id": "t04-110"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [4, 7, 10, 13]\n",
    "for number in numbers:\n",
    "    if number % 2 == 0:\n",
    "        print(number, \"is even\")\n",
    "    else:\n",
    "        print(number, \"is odd\")"
   ],
   "id": "t04-111"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.8 Finding the largest item by hand\n",
    "\n",
    "Change it and run: change `>` to `<`. What does the loop find now?"
   ],
   "id": "t04-112"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [12, 45, 7, 38]\n",
    "largest = numbers[0]\n",
    "for number in numbers:\n",
    "    if number > largest:\n",
    "        largest = number\n",
    "print(\"Largest:\", largest)"
   ],
   "id": "t04-113"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We start with the first item, and replace `largest` each time we meet a bigger one. (The built-in `max(numbers)` does the same job, but you should understand how it works.)\n",
    "\n",
    "### 5.9 Building a new list from an old one\n",
    "\n",
    "Transforming every item:\n",
    "\n",
    "Change it and run: change the tax from `1.2` to `1.18`."
   ],
   "id": "t04-114"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = [100, 250, 80]\n",
    "with_tax = []\n",
    "for price in prices:\n",
    "    with_tax.append(price * 1.2)\n",
    "print(with_tax)"
   ],
   "id": "t04-115"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Keeping only some items:\n",
    "\n",
    "Change it and run: keep the numbers greater than 6 instead."
   ],
   "id": "t04-116"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 8, 5, 12, 7, 10]\n",
    "evens = []\n",
    "for number in numbers:\n",
    "    if number % 2 == 0:\n",
    "        evens.append(number)\n",
    "print(evens)"
   ],
   "id": "t04-117"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Remember these two patterns. In Part 8, `map` does the first one and `filter` does the second one in a single line.\n",
    "\n",
    "### 5.10 Changing the items of a list in place\n",
    "\n",
    "To change the items you need the index:"
   ],
   "id": "t04-118"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4]\n",
    "for i in range(len(numbers)):\n",
    "    numbers[i] = numbers[i] * 2\n",
    "print(numbers)"
   ],
   "id": "t04-119"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This does not work with `for number in numbers`, because the loop variable is only a copy of the value:"
   ],
   "id": "t04-120"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4]\n",
    "for number in numbers:\n",
    "    number = number * 2\n",
    "print(numbers)"
   ],
   "id": "t04-121"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.11 Searching with `break`\n",
    "\n",
    "Change it and run: remove the `break` line. How many lines are printed?"
   ],
   "id": "t04-122"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [4, 9, 15, 22, 31]\n",
    "for number in numbers:\n",
    "    if number > 10:\n",
    "        print(\"First number above 10:\", number)\n",
    "        break"
   ],
   "id": "t04-123"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.12 A `while` loop that empties a list\n",
    "\n",
    "An empty list counts as `False`, so `while tasks:` means \"while the list is not empty\":\n",
    "\n",
    "Change it and run: change `pop(0)` to `pop()`. In which order are the tasks done now?"
   ],
   "id": "t04-124"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tasks = [\"wash\", \"cook\", \"study\"]\n",
    "while tasks:\n",
    "    current = tasks.pop(0)\n",
    "    print(\"Doing:\", current)\n",
    "print(\"All done. Tasks left:\", tasks)"
   ],
   "id": "t04-125"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.13 Going through two lists together: `zip`\n",
    "\n",
    "Change it and run: remove one grade. `zip` stops at the shorter list."
   ],
   "id": "t04-126"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "names = [\"Aylin\", \"Murad\", \"Leyla\"]\n",
    "grades = [85, 92, 78]\n",
    "for name, grade in zip(names, grades):\n",
    "    print(name, grade)"
   ],
   "id": "t04-127"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.14 Warning: do not remove items from a list while looping over it\n",
    "\n",
    "Change it and run: start with `[2, 2, 4, 4]` and predict the result."
   ],
   "id": "t04-128"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [2, 4, 6, 7, 8]\n",
    "for number in numbers:\n",
    "    if number % 2 == 0:\n",
    "        numbers.remove(number)\n",
    "print(numbers)"
   ],
   "id": "t04-129"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We wanted to remove all even numbers, but 4 is still there. When an item is removed, the others move left and the loop skips one. The safe way is to build a new list:"
   ],
   "id": "t04-130"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [2, 4, 6, 7, 8]\n",
    "odds = []\n",
    "for number in numbers:\n",
    "    if number % 2 != 0:\n",
    "        odds.append(number)\n",
    "print(odds)"
   ],
   "id": "t04-131"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Input, text, nested lists and functions\n",
    "\n",
    "### 6.1 Reading a list from the user\n",
    "\n",
    "In Part 1 we read exactly two numbers with `a, b = map(int, input().split())`. When we do not know how many numbers there are, we put all of them in a list:\n",
    "\n",
    "Change it and run: type your own numbers, as many as you like.\n",
    "\n",
    "When the cell asks for input, type `4 8 15 16 23 42`."
   ],
   "id": "t04-132"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "4 8 15 16 23 42"
     ]
    }
   },
   "outputs": [],
   "source": [
    "numbers = list(map(int, input().split()))\n",
    "print(numbers)\n",
    "print(\"How many:\", len(numbers))\n",
    "print(\"Sum:\", sum(numbers))"
   ],
   "id": "t04-133"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Read it from the inside out:\n",
    "\n",
    "| Piece | Result for the input `4 8 15 16 23 42` |\n",
    "| --- | --- |\n",
    "| `input()` | `\"4 8 15 16 23 42\"` |\n",
    "| `.split()` | `['4', '8', '15', '16', '23', '42']` |\n",
    "| `map(int, ...)` | `int` applied to every piece |\n",
    "| `list(...)` | `[4, 8, 15, 16, 23, 42]` |\n",
    "\n",
    "Without `list(...)` you get a `map` object, not a list. It has no `len()` and no indexes:\n",
    "\n",
    "```python\n",
    "numbers = map(int, input().split())\n",
    "print(len(numbers))\n",
    "```\n",
    "\n",
    "```\n",
    "4 8 15\n",
    "TypeError: object of type 'map' has no len()\n",
    "```\n",
    "\n",
    "The same line for other types:\n",
    "\n",
    "When the cell asks for input, type `2.5 10 7.25`."
   ],
   "id": "t04-134"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "2.5 10 7.25"
     ]
    }
   },
   "outputs": [],
   "source": [
    "prices = list(map(float, input().split()))\n",
    "print(prices)"
   ],
   "id": "t04-135"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When the cell asks for input, type `red green blue`."
   ],
   "id": "t04-136"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "red green blue"
     ]
    }
   },
   "outputs": [],
   "source": [
    "words = input().split()\n",
    "print(words)"
   ],
   "id": "t04-137"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.2 Values separated by commas\n",
    "\n",
    "`.split(\",\")` cuts at commas instead of spaces:\n",
    "\n",
    "Change it and run: type `1,2,3,4`.\n",
    "\n",
    "When the cell asks for input, type `10,20,30`."
   ],
   "id": "t04-138"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "10,20,30"
     ]
    }
   },
   "outputs": [],
   "source": [
    "numbers = list(map(int, input().split(\",\")))\n",
    "print(numbers)"
   ],
   "id": "t04-139"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.3 The count first, then the numbers\n",
    "\n",
    "Many problems give the count `n` on the first line and the `n` numbers on the second line:\n",
    "\n",
    "When the cell asks for input, type `3`, then `10 20 30`."
   ],
   "id": "t04-140"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "3",
      "10 20 30"
     ]
    }
   },
   "outputs": [],
   "source": [
    "n = int(input())\n",
    "numbers = list(map(int, input().split()))\n",
    "print(\"n =\", n)\n",
    "print(numbers)"
   ],
   "id": "t04-141"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.4 One number per line\n",
    "\n",
    "When each number is on its own line, use a loop and `append`:\n",
    "\n",
    "When the cell asks for input, type `3`, then `10`, then `20`, then `30`."
   ],
   "id": "t04-142"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "3",
      "10",
      "20",
      "30"
     ]
    }
   },
   "outputs": [],
   "source": [
    "n = int(input())\n",
    "numbers = []\n",
    "for i in range(n):\n",
    "    numbers.append(int(input()))\n",
    "print(numbers)"
   ],
   "id": "t04-143"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.5 Text and lists: `split` and `join`\n",
    "\n",
    "`split` turns a text into a list. `join` does the opposite: it glues a list of texts into one text.\n",
    "\n",
    "Change it and run: join the words with `\" + \"`."
   ],
   "id": "t04-144"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sentence = \"Python is fun\"\n",
    "words = sentence.split()\n",
    "print(words)\n",
    "print(len(words))\n",
    "\n",
    "joined = \"-\".join(words)\n",
    "print(joined)\n",
    "print(\" \".join(words))"
   ],
   "id": "t04-145"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The text before `.join` is the separator placed between the items.\n",
    "\n",
    "`join` works only with text. A list of numbers must be converted first, and `map(str, ...)` does that:"
   ],
   "id": "t04-146"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3]\n",
    "print(\", \".join(map(str, numbers)))"
   ],
   "id": "t04-147"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Printing a list without brackets: put a star before the list name. `print(*numbers)` is the same as `print(1, 2, 3)`.\n",
    "\n",
    "Change it and run: use `sep=\" - \"`."
   ],
   "id": "t04-148"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3]\n",
    "print(numbers)\n",
    "print(*numbers)\n",
    "print(*numbers, sep=\", \")"
   ],
   "id": "t04-149"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.6 Lists inside lists (nested lists)\n",
    "\n",
    "An item of a list can be another list. This is how we store a table:\n",
    "\n",
    "Change it and run: print the middle number 5 with two indexes."
   ],
   "id": "t04-150"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "table = [\n",
    "    [1, 2, 3],\n",
    "    [4, 5, 6],\n",
    "    [7, 8, 9],\n",
    "]\n",
    "print(table[0])\n",
    "print(table[1][2])\n",
    "print(len(table))"
   ],
   "id": "t04-151"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`table[1]` is the second row, and `table[1][2]` is the third item of that row.\n",
    "\n",
    "A nested loop visits every item:"
   ],
   "id": "t04-152"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "table = [\n",
    "    [1, 2, 3],\n",
    "    [4, 5, 6],\n",
    "    [7, 8, 9],\n",
    "]\n",
    "for row in table:\n",
    "    for item in row:\n",
    "        print(item, end=\" \")\n",
    "    print()"
   ],
   "id": "t04-153"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "students = [[\"Aylin\", 85], [\"Murad\", 92], [\"Leyla\", 78]]\n",
    "for student in students:\n",
    "    print(student[0], \"has\", student[1])"
   ],
   "id": "t04-154"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.7 Lists and functions\n",
    "\n",
    "A function can take a list as a parameter and can return a list.\n",
    "\n",
    "Change it and run: call it with your own list."
   ],
   "id": "t04-155"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def average(numbers):\n",
    "    return sum(numbers) / len(numbers)\n",
    "\n",
    "print(average([10, 20, 30]))\n",
    "print(average([85, 92, 78, 60]))"
   ],
   "id": "t04-156"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Change it and run: change `> 0` to `>= 0`. Which number is added?"
   ],
   "id": "t04-157"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def only_positive(numbers):\n",
    "    result = []\n",
    "    for number in numbers:\n",
    "        if number > 0:\n",
    "            result.append(number)\n",
    "    return result\n",
    "\n",
    "print(only_positive([3, -1, 0, 7, -5]))"
   ],
   "id": "t04-158"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.8 A function can change the list you give it\n",
    "\n",
    "Because lists are mutable, a change made inside the function is visible outside:\n",
    "\n",
    "Change it and run: pass `my_grades.copy()` instead. The original list stays the same."
   ],
   "id": "t04-159"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add_bonus(grades):\n",
    "    for i in range(len(grades)):\n",
    "        grades[i] = grades[i] + 5\n",
    "\n",
    "my_grades = [70, 80, 90]\n",
    "add_bonus(my_grades)\n",
    "print(my_grades)"
   ],
   "id": "t04-160"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you do not want that, build and return a new list (like `only_positive` above), or pass a copy: `add_bonus(my_grades.copy())`.\n",
    "\n",
    "## 7. Tuples\n",
    "\n",
    "### 7.1 Lists so far (a short review before tuples)\n",
    "\n",
    "| Property | List |\n",
    "| --- | --- |\n",
    "| Written with | square brackets `[1, 2, 3]` |\n",
    "| Ordered | yes, every item has an index |\n",
    "| Mutable (changeable) | yes: change, add, remove items |\n",
    "| Duplicates | allowed |\n",
    "| Methods | many: `append`, `insert`, `extend`, `remove`, `pop`, `sort`, ... |\n",
    "| Typical use | a collection that grows, shrinks, or gets edited |\n",
    "\n",
    "Now we meet the tuple. A tuple is almost the same thing, but it cannot be changed.\n",
    "\n",
    "### 7.2 What is a tuple?\n",
    "\n",
    "A tuple is an ordered collection of values, like a list, but immutable: after it is created, you cannot change, add, or remove items.\n",
    "\n",
    "Real-life picture: a list is a shopping list written in pencil. A tuple is a date of birth or the coordinates of a city: the values belong together and should not change.\n",
    "\n",
    "### 7.3 Creating tuples\n",
    "\n",
    "A tuple is written in round brackets (parentheses):"
   ],
   "id": "t04-161"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "point = (3, 5)\n",
    "colors = (\"red\", \"green\", \"blue\")\n",
    "empty = ()\n",
    "mixed = (1, \"two\", 3.0)\n",
    "\n",
    "print(point)\n",
    "print(colors)\n",
    "print(empty)\n",
    "print(type(point))\n",
    "print(len(colors))"
   ],
   "id": "t04-162"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The parentheses are optional. The commas make the tuple:"
   ],
   "id": "t04-163"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "point = 3, 5\n",
    "print(point)\n",
    "print(type(point))"
   ],
   "id": "t04-164"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.4 A tuple with one item needs a comma\n",
    "\n",
    "Change it and run: remove the comma from `(5,)`."
   ],
   "id": "t04-165"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "not_a_tuple = (5)\n",
    "a_tuple = (5,)\n",
    "print(type(not_a_tuple))\n",
    "print(type(a_tuple))"
   ],
   "id": "t04-166"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`(5)` is only the number 5 in brackets. `(5,)` is a tuple with one item.\n",
    "\n",
    "### 7.5 Making a tuple from something else: `tuple()`"
   ],
   "id": "t04-167"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(tuple([1, 2, 3]))\n",
    "print(tuple(\"abc\"))\n",
    "print(tuple(range(4)))"
   ],
   "id": "t04-168"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.6 Reading a tuple works exactly like a list\n",
    "\n",
    "Indexes, negative indexes, slices and `len` are the same:\n",
    "\n",
    "Change it and run: print `colors[::-1]`."
   ],
   "id": "t04-169"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "colors = (\"red\", \"green\", \"blue\", \"black\")\n",
    "print(colors[0])\n",
    "print(colors[-1])\n",
    "print(colors[1:3])\n",
    "print(len(colors))"
   ],
   "id": "t04-170"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A slice of a tuple is a tuple.\n",
    "\n",
    "### 7.7 A tuple cannot be changed\n",
    "\n",
    "```python\n",
    "point = (3, 5)\n",
    "point[0] = 10\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: 'tuple' object does not support item assignment\n",
    "```\n",
    "\n",
    "There is no `append`, `remove`, `insert`, `pop` or `sort` for tuples:\n",
    "\n",
    "```python\n",
    "point = (3, 5)\n",
    "point.append(7)\n",
    "```\n",
    "\n",
    "```\n",
    "AttributeError: 'tuple' object has no attribute 'append'\n",
    "```\n",
    "\n",
    "### 7.8 The two tuple methods: `count` and `index`\n",
    "\n",
    "Only the methods that do not change anything exist:"
   ],
   "id": "t04-171"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = (4, 7, 4, 9, 4)\n",
    "print(numbers.count(4))\n",
    "print(numbers.index(7))"
   ],
   "id": "t04-172"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.9 Operators and built-in functions work"
   ],
   "id": "t04-173"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = (1, 2)\n",
    "b = (3, 4)\n",
    "print(a + b)\n",
    "print(a * 3)\n",
    "print(2 in a)\n",
    "print(a == (1, 2))\n",
    "print(a < b)\n",
    "\n",
    "grades = (85, 92, 78)\n",
    "print(sum(grades), min(grades), max(grades))\n",
    "print(sorted(grades))"
   ],
   "id": "t04-174"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`a + b` builds a new tuple. Notice that `sorted()` gives back a list, even for a tuple.\n",
    "\n",
    "### 7.10 Loops and `if/else` work exactly as with lists"
   ],
   "id": "t04-175"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = (85, 42, 78, 60)\n",
    "for grade in grades:\n",
    "    if grade >= 50:\n",
    "        print(grade, \"passed\")\n",
    "    else:\n",
    "        print(grade, \"failed\")"
   ],
   "id": "t04-176"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = (3, 8, 5, 12, 7)\n",
    "total = 0\n",
    "i = 0\n",
    "while i < len(numbers):\n",
    "    if numbers[i] % 2 == 1:\n",
    "        total = total + numbers[i]\n",
    "    i = i + 1\n",
    "print(\"Sum of odd numbers:\", total)"
   ],
   "id": "t04-177"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.11 Packing and unpacking\n",
    "\n",
    "Putting values into a tuple is called packing. Taking them out into variables is unpacking:\n",
    "\n",
    "Change it and run: add a fourth value and a fourth variable."
   ],
   "id": "t04-178"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "person = (\"Aylin\", 20, \"Baku\")     # packing\n",
    "name, age, city = person           # unpacking\n",
    "print(name)\n",
    "print(age)\n",
    "print(city)"
   ],
   "id": "t04-179"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The number of variables must match the number of items:\n",
    "\n",
    "```python\n",
    "person = (\"Aylin\", 20, \"Baku\")\n",
    "name, age = person\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: too many values to unpack (expected 2, got 3)\n",
    "```\n",
    "\n",
    "You already used unpacking: `a, b = map(int, input().split())` in Part 1 and `for i, fruit in enumerate(fruits)` in Part 5. `enumerate` and `zip` give tuples:"
   ],
   "id": "t04-180"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"banana\"]\n",
    "print(list(enumerate(fruits)))\n",
    "print(list(zip([\"a\", \"b\"], [1, 2])))"
   ],
   "id": "t04-181"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.12 Swapping two variables"
   ],
   "id": "t04-182"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 5\n",
    "b = 10\n",
    "a, b = b, a\n",
    "print(a, b)"
   ],
   "id": "t04-183"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The right side `b, a` is packed into a tuple, then unpacked into `a` and `b`.\n",
    "\n",
    "### 7.13 A function can return several values\n",
    "\n",
    "In the last lesson we said a function returns one value. With a tuple, that one value can hold several:\n",
    "\n",
    "Change it and run: call it with your own numbers."
   ],
   "id": "t04-184"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def min_and_max(numbers):\n",
    "    return min(numbers), max(numbers)\n",
    "\n",
    "result = min_and_max([4, 9, 1, 7])\n",
    "print(result)\n",
    "\n",
    "smallest, largest = min_and_max([4, 9, 1, 7])\n",
    "print(smallest, largest)"
   ],
   "id": "t04-185"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The built-in `divmod` works this way too:\n",
    "\n",
    "Change it and run: try `divmod(200, 60)`: hours and minutes."
   ],
   "id": "t04-186"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "quotient, remainder = divmod(17, 5)\n",
    "print(quotient, remainder)"
   ],
   "id": "t04-187"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.14 How do I \"change\" a tuple?\n",
    "\n",
    "You cannot change it, but you can build a new one. Either join tuples, or convert to a list, change the list, and convert back:"
   ],
   "id": "t04-188"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "point = (3, 5)\n",
    "point = point + (7,)\n",
    "print(point)\n",
    "\n",
    "colors = (\"red\", \"green\", \"blue\")\n",
    "temp = list(colors)\n",
    "temp[1] = \"yellow\"\n",
    "colors = tuple(temp)\n",
    "print(colors)"
   ],
   "id": "t04-189"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.15 Tuples inside a list\n",
    "\n",
    "A list of tuples is a very common way to store records:\n",
    "\n",
    "Change it and run: add a fourth student to the list."
   ],
   "id": "t04-190"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "students = [(\"Aylin\", 85), (\"Murad\", 92), (\"Leyla\", 78)]\n",
    "for name, grade in students:\n",
    "    print(name, grade)"
   ],
   "id": "t04-191"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The list can grow (new students), but each record stays fixed.\n",
    "\n",
    "### 7.16 List vs tuple (the differences)\n",
    "\n",
    "|  | List | Tuple |\n",
    "| --- | --- | --- |\n",
    "| Brackets | `[1, 2, 3]` | `(1, 2, 3)` |\n",
    "| Mutable (can change) | yes | no |\n",
    "| Add / remove items | `append`, `insert`, `extend`, `remove`, `pop`, `del`, `clear` | not possible |\n",
    "| Sort in place | `sort()`, `reverse()` | not possible (`sorted()` gives a list) |\n",
    "| Methods | 11 common ones | only `count` and `index` |\n",
    "| Indexes and slices | yes | yes |\n",
    "| `len`, `sum`, `min`, `max`, `in`, `+`, `*` | yes | yes |\n",
    "| Loops | yes | yes |\n",
    "| One item | `[5]` | `(5,)` (comma needed) |\n",
    "| Speed and memory | a little slower and bigger | a little faster and smaller |\n",
    "| Typical use | items of the same kind, the amount changes | a fixed group of values that belong together |"
   ],
   "id": "t04-192"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "my_list = [1, 2, 3]\n",
    "my_tuple = (1, 2, 3)\n",
    "\n",
    "my_list[0] = 100\n",
    "print(my_list)\n",
    "\n",
    "print(my_list == [100, 2, 3])\n",
    "print(my_tuple == (1, 2, 3))\n",
    "print([1, 2, 3] == (1, 2, 3))"
   ],
   "id": "t04-193"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A list and a tuple are never equal, even with the same items.\n",
    "\n",
    "How to choose:\n",
    "\n",
    "- \"Grades of a class\", \"items in a cart\", \"numbers typed by the user\" will grow or change: use a list.\n",
    "- \"A point (x, y)\", \"a date (day, month, year)\", \"a color (red, green, blue)\", \"the two results of a function\" stay fixed: use a tuple.\n",
    "- If you are not sure, use a list.\n",
    "\n",
    "Converting between them is easy: `list(my_tuple)` and `tuple(my_list)`.\n",
    "\n",
    "## 8. `map` and `filter`\n",
    "\n",
    "### 8.1 `map` in detail\n",
    "\n",
    "In Part 1 we used `map(int, ...)` to read numbers. Now we look at `map` as a general tool.\n",
    "\n",
    "```\n",
    "map(function, sequence)\n",
    "```\n",
    "\n",
    "`map` applies the function to every item and gives back the results. The number of results is always the same as the number of items.\n",
    "\n",
    "### 8.2 `map` with built-in functions\n",
    "\n",
    "Change it and run: apply `float` to the list of words."
   ],
   "id": "t04-194"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "words = [\"10\", \"20\", \"30\"]\n",
    "numbers = list(map(int, words))\n",
    "print(numbers)\n",
    "\n",
    "print(list(map(str, [1, 2, 3])))\n",
    "print(list(map(len, [\"apple\", \"kiwi\", \"fig\"])))\n",
    "print(list(map(abs, [-3, 5, -8])))"
   ],
   "id": "t04-195"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.3 `map` gives a `map` object, not a list"
   ],
   "id": "t04-196"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = map(abs, [-3, 5, -8])\n",
    "print(result)\n",
    "print(list(result))"
   ],
   "id": "t04-197"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The numbers after `at` in the first line will be different on your computer. A `map` object is a \"recipe\" that produces the values one by one when something asks for them: `list()`, `tuple()`, a `for` loop, `sum()` or unpacking. Wrap it in `list()` when you need a real list."
   ],
   "id": "t04-198"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(tuple(map(abs, [-3, 5, -8])))\n",
    "print(sum(map(abs, [-3, 5, -8])))\n",
    "\n",
    "for value in map(abs, [-3, 5, -8]):\n",
    "    print(value)"
   ],
   "id": "t04-199"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A `map` object can be used only once. After that it is empty:"
   ],
   "id": "t04-200"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = map(abs, [-3, 5, -8])\n",
    "print(list(result))\n",
    "print(list(result))"
   ],
   "id": "t04-201"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.4 `map` with your own function\n",
    "\n",
    "Change it and run: change the tax to 18% inside `add_tax`."
   ],
   "id": "t04-202"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add_tax(price):\n",
    "    return price * 1.2\n",
    "\n",
    "prices = [100, 250, 80]\n",
    "print(list(map(add_tax, prices)))"
   ],
   "id": "t04-203"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is the same as the loop from Part 5:"
   ],
   "id": "t04-204"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add_tax(price):\n",
    "    return price * 1.2\n",
    "\n",
    "prices = [100, 250, 80]\n",
    "with_tax = []\n",
    "for price in prices:\n",
    "    with_tax.append(add_tax(price))\n",
    "print(with_tax)"
   ],
   "id": "t04-205"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.5 Small one-line functions: `lambda`\n",
    "\n",
    "You met lambda functions in the last lesson (Topic 3, Part 6). A short reminder: writing a whole `def` for a tiny function is long. A lambda is a small function without a name, written in one line:\n",
    "\n",
    "```\n",
    "lambda parameter: result\n",
    "```"
   ],
   "id": "t04-206"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "double = lambda n: n * 2\n",
    "print(double(5))"
   ],
   "id": "t04-207"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`lambda n: n * 2` means: \"take `n`, give back `n * 2`\". It is the same as:"
   ],
   "id": "t04-208"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def double(n):\n",
    "    return n * 2\n",
    "\n",
    "print(double(5))"
   ],
   "id": "t04-209"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Lambdas are useful inside `map`:\n",
    "\n",
    "Change it and run: add a line that maps `lambda n: n + 100` over the numbers."
   ],
   "id": "t04-210"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4]\n",
    "print(list(map(lambda n: n * 2, numbers)))\n",
    "print(list(map(lambda n: n ** 2, numbers)))\n",
    "\n",
    "names = [\"aylin\", \"murad\"]\n",
    "print(list(map(lambda name: name.upper(), names)))"
   ],
   "id": "t04-211"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.6 `map` with two lists\n",
    "\n",
    "With a function of two parameters, `map` takes one item from each list:\n",
    "\n",
    "Change it and run: multiply the pairs instead of adding them."
   ],
   "id": "t04-212"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [1, 2, 3]\n",
    "b = [10, 20, 30]\n",
    "print(list(map(lambda x, y: x + y, a, b)))"
   ],
   "id": "t04-213"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.7 `map` works with tuples too"
   ],
   "id": "t04-214"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "point = (1.6, 2.4, 3.5)\n",
    "print(tuple(map(round, point)))"
   ],
   "id": "t04-215"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.8 `filter`\n",
    "\n",
    "```\n",
    "filter(function, sequence)\n",
    "```\n",
    "\n",
    "`filter` keeps only the items for which the function returns `True`. The function must answer a yes/no question about one item.\n",
    "\n",
    "Change it and run: write `is_odd` and filter with it."
   ],
   "id": "t04-216"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_even(n):\n",
    "    return n % 2 == 0\n",
    "\n",
    "numbers = [3, 8, 5, 12, 7, 10]\n",
    "print(list(filter(is_even, numbers)))"
   ],
   "id": "t04-217"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`filter` asked `is_even` about every number, and kept the ones where the answer was `True`. The items themselves are not changed.\n",
    "\n",
    "With a lambda:\n",
    "\n",
    "Change it and run: keep the numbers that are divisible by 4."
   ],
   "id": "t04-218"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 8, 5, 12, 7, 10]\n",
    "print(list(filter(lambda n: n % 2 == 1, numbers)))\n",
    "print(list(filter(lambda n: n > 6, numbers)))"
   ],
   "id": "t04-219"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is the same as the loop with `if` from Part 5:"
   ],
   "id": "t04-220"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 8, 5, 12, 7, 10]\n",
    "odds = []\n",
    "for number in numbers:\n",
    "    if number % 2 == 1:\n",
    "        odds.append(number)\n",
    "print(odds)"
   ],
   "id": "t04-221"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Like `map`, `filter` gives an object that you wrap in `list()`:"
   ],
   "id": "t04-222"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = filter(lambda n: n > 6, [3, 8, 5, 12])\n",
    "print(result)\n",
    "print(list(result))"
   ],
   "id": "t04-223"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "More examples:\n",
    "\n",
    "Change it and run: change the pass mark to 80. How many pass?"
   ],
   "id": "t04-224"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = [85, 42, 78, 60, 95, 30]\n",
    "passed = list(filter(lambda g: g >= 50, grades))\n",
    "print(passed)\n",
    "print(len(passed))\n",
    "\n",
    "words = [\"apple\", \"kiwi\", \"banana\", \"fig\"]\n",
    "print(list(filter(lambda w: len(w) > 4, words)))\n",
    "\n",
    "temperatures = (-3, 5, -8, 12, 0)\n",
    "print(tuple(filter(lambda t: t < 0, temperatures)))"
   ],
   "id": "t04-225"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.9 `filter(None, ...)` removes \"empty\" values\n",
    "\n",
    "With `None` instead of a function, `filter` keeps the truthy values and drops `0`, `\"\"`, `None` and `False`:"
   ],
   "id": "t04-226"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "values = [0, 5, \"\", \"hi\", None, 7]\n",
    "print(list(filter(None, values)))"
   ],
   "id": "t04-227"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.10 `map` vs `filter` (the differences)\n",
    "\n",
    "|  | `map` | `filter` |\n",
    "| --- | --- | --- |\n",
    "| Job | changes every item | chooses some items |\n",
    "| The function returns | the new value | `True` or `False` |\n",
    "| Number of results | always the same as the input | the same or fewer |\n",
    "| Are the items changed? | yes | no, they are kept as they are |\n",
    "| The same job with a loop | `result.append(function(item))` | `if function(item): result.append(item)` |\n",
    "| Question it answers | \"What does each item become?\" | \"Which items do I keep?\" |\n",
    "\n",
    "The same list and the same kind of function, two different results:"
   ],
   "id": "t04-228"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5, 6]\n",
    "print(list(map(lambda n: n * 10, numbers)))\n",
    "print(list(filter(lambda n: n % 2 == 0, numbers)))"
   ],
   "id": "t04-229"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A classic mistake is giving `map` a yes/no function. You get `True` and `False` values, not the numbers:"
   ],
   "id": "t04-230"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5, 6]\n",
    "print(list(map(lambda n: n % 2 == 0, numbers)))\n",
    "print(list(filter(lambda n: n % 2 == 0, numbers)))"
   ],
   "id": "t04-231"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.11 Which one for which problem?\n",
    "\n",
    "| The problem says | Use | Example |\n",
    "| --- | --- | --- |\n",
    "| \"convert every ...\", \"read the numbers\" | `map` | `list(map(int, input().split()))` |\n",
    "| \"the square / double / length of every item\" | `map` | `map(lambda n: n ** 2, numbers)` |\n",
    "| \"make every name uppercase\" | `map` | `map(lambda s: s.upper(), names)` |\n",
    "| \"only the even numbers\", \"only the positive ones\" | `filter` | `filter(lambda n: n > 0, numbers)` |\n",
    "| \"remove the items that ...\", \"keep the items that ...\" | `filter` | `filter(lambda g: g >= 50, grades)` |\n",
    "| \"how many items are ...\" | `filter` + `len` | `len(list(filter(..., numbers)))` |\n",
    "| \"the sum of the squares of the odd numbers\" | `filter`, then `map` | see below |\n",
    "\n",
    "### 8.12 Using both together\n",
    "\n",
    "First choose, then change. \"The squares of the odd numbers\":\n",
    "\n",
    "Change it and run: choose the even numbers instead and make their cubes."
   ],
   "id": "t04-232"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5, 6]\n",
    "odds = filter(lambda n: n % 2 == 1, numbers)\n",
    "squares = map(lambda n: n ** 2, odds)\n",
    "print(list(squares))"
   ],
   "id": "t04-233"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In one line, with the sum:"
   ],
   "id": "t04-234"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5, 6]\n",
    "print(sum(map(lambda n: n ** 2, filter(lambda n: n % 2 == 1, numbers))))"
   ],
   "id": "t04-235"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.13 `map`/`filter` or a loop?\n",
    "\n",
    "Both are correct. A loop is longer but can do several things at once and is easier to debug. `map` and `filter` are short and clear for one simple job on every item. If the one-line version becomes hard to read, write the loop.\n",
    "\n",
    "## 9. Common mistakes\n",
    "\n",
    "The red text is the real message Python shows. Where there is no message, the program runs but gives a wrong answer: the comment shows what it prints.\n",
    "\n",
    "| Mistake | What happens | Fix |\n",
    "| --- | --- | --- |\n",
    "| Using index `len(list)` | `IndexError` | the last index is `len(list) - 1`, or use `[-1]` |\n",
    "| `numbers = numbers.sort()` | the list becomes `None` | write `numbers.sort()` alone, or `sorted(numbers)` |\n",
    "| `a = a.append(5)` | `a` becomes `None` | write `a.append(5)` alone |\n",
    "| `b = a` to copy a list | both names change together | `b = a.copy()` |\n",
    "| `append` when you meant `extend` | a list inside the list | `extend` adds each item |\n",
    "| `remove` a value that is not there | `ValueError` | check with `in` first |\n",
    "| Removing items while looping over the same list | some items are skipped | build a new list |\n",
    "| Adding with `list[len(list)] = x` | `IndexError` | use `append(x)` |\n",
    "| Changing a tuple | `TypeError` | make a new tuple, or use a list |\n",
    "| `(5)` for a one-item tuple | it is just the number 5 | write `(5,)` |\n",
    "| Forgetting `list()` around `map` / `filter` | you get a `map` object, no `len`, no indexes | `list(map(...))` |\n",
    "| Forgetting `map(int, ...)` after `split()` | the items are text: `\"5\" + \"7\"` gives `\"57\"` | `list(map(int, input().split()))` |\n",
    "| Writing `map(int(), ...)` | `int()` is called too early | give the function itself: `map(int, ...)` |\n",
    "| Using `map` to choose items | a list of `True`/`False` | use `filter` |\n",
    "| Wrong number of variables when unpacking | `ValueError` | match the number of values |\n",
    "\n",
    "Forgetting `map(int, ...)`:\n",
    "\n",
    "When the cell asks for input, type `5 7`."
   ],
   "id": "t04-236"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "5 7"
     ]
    }
   },
   "outputs": [],
   "source": [
    "a, b = input().split()\n",
    "print(a + b)"
   ],
   "id": "t04-237"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The two texts were joined, not added.\n",
    "\n",
    "## 10. Solved problems (easy to medium-hard)\n",
    "\n",
    "Every example was run, and the outputs are real.\n",
    "\n",
    "### 10.1 Level 1: Easy\n",
    "\n",
    "Problem 1. Sum of two numbers on one line\n",
    "\n",
    "When the cell asks for input, type `12 30`."
   ],
   "id": "t04-238"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "12 30"
     ]
    }
   },
   "outputs": [],
   "source": [
    "a, b = map(int, input().split())\n",
    "print(a + b)"
   ],
   "id": "t04-239"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `split` cuts the line, `map(int, ...)` converts both pieces, and unpacking stores them in `a` and `b`.\n",
    "\n",
    "Problem 2. First, last and middle item"
   ],
   "id": "t04-240"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [10, 20, 30, 40, 50]\n",
    "print(\"First:\", numbers[0])\n",
    "print(\"Last:\", numbers[-1])\n",
    "print(\"Middle:\", numbers[len(numbers) // 2])"
   ],
   "id": "t04-241"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the first index is 0, the last is -1, and `len // 2` is the middle index of a list with an odd number of items.\n",
    "\n",
    "Problem 3. Sum and average of a list read from the user\n",
    "\n",
    "Change it and run: type your own numbers.\n",
    "\n",
    "When the cell asks for input, type `10 20 30 40`."
   ],
   "id": "t04-242"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "10 20 30 40"
     ]
    }
   },
   "outputs": [],
   "source": [
    "numbers = list(map(int, input().split()))\n",
    "total = sum(numbers)\n",
    "print(\"Sum:\", total)\n",
    "print(\"Average:\", total / len(numbers))"
   ],
   "id": "t04-243"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 4. Count the even and the odd numbers"
   ],
   "id": "t04-244"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 8, 5, 12, 7, 10, 1]\n",
    "even = 0\n",
    "odd = 0\n",
    "for number in numbers:\n",
    "    if number % 2 == 0:\n",
    "        even = even + 1\n",
    "    else:\n",
    "        odd = odd + 1\n",
    "print(\"Even:\", even)\n",
    "print(\"Odd:\", odd)"
   ],
   "id": "t04-245"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: two counters and one `if/else` inside the loop.\n",
    "\n",
    "Problem 5. Sum of the odd numbers, three ways"
   ],
   "id": "t04-246"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 8, 5, 12, 7, 10]\n",
    "\n",
    "# 1. loop and if\n",
    "total = 0\n",
    "for number in numbers:\n",
    "    if number % 2 == 1:\n",
    "        total = total + number\n",
    "print(total)\n",
    "\n",
    "# 2. while loop\n",
    "total = 0\n",
    "i = 0\n",
    "while i < len(numbers):\n",
    "    if numbers[i] % 2 == 1:\n",
    "        total = total + numbers[i]\n",
    "    i = i + 1\n",
    "print(total)\n",
    "\n",
    "# 3. filter\n",
    "print(sum(filter(lambda n: n % 2 == 1, numbers)))"
   ],
   "id": "t04-247"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: all three do the same job. `filter` chooses the odd numbers and `sum` adds them.\n",
    "\n",
    "Problem 6. Build a shopping list"
   ],
   "id": "t04-248"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "shopping = []\n",
    "shopping.append(\"milk\")\n",
    "shopping.append(\"bread\")\n",
    "shopping.insert(0, \"eggs\")\n",
    "shopping.extend([\"rice\", \"tea\"])\n",
    "shopping.remove(\"bread\")\n",
    "print(shopping)\n",
    "print(\"Items:\", len(shopping))"
   ],
   "id": "t04-249"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 7. Largest and smallest without `max` and `min`"
   ],
   "id": "t04-250"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [12, 45, 7, 38, 21]\n",
    "largest = numbers[0]\n",
    "smallest = numbers[0]\n",
    "for number in numbers:\n",
    "    if number > largest:\n",
    "        largest = number\n",
    "    if number < smallest:\n",
    "        smallest = number\n",
    "print(\"Largest:\", largest)\n",
    "print(\"Smallest:\", smallest)"
   ],
   "id": "t04-251"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: two separate `if` statements (not `elif`), because each number must be compared with both.\n",
    "\n",
    "Problem 8. Swap the first and the last item"
   ],
   "id": "t04-252"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5]\n",
    "numbers[0], numbers[-1] = numbers[-1], numbers[0]\n",
    "print(numbers)"
   ],
   "id": "t04-253"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: tuple packing and unpacking swaps two values without a helper variable.\n",
    "\n",
    "Problem 9. Unpack a tuple"
   ],
   "id": "t04-254"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "date = (15, 3, 2026)\n",
    "day, month, year = date\n",
    "print(\"Day:\", day)\n",
    "print(\"Month:\", month)\n",
    "print(\"Year:\", year)"
   ],
   "id": "t04-255"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 10.2 Level 2: Medium\n",
    "\n",
    "Problem 10. Reverse a list in three ways"
   ],
   "id": "t04-256"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5]\n",
    "\n",
    "print(numbers[::-1])\n",
    "\n",
    "reversed_list = []\n",
    "for number in numbers:\n",
    "    reversed_list.insert(0, number)\n",
    "print(reversed_list)\n",
    "\n",
    "numbers.reverse()\n",
    "print(numbers)"
   ],
   "id": "t04-257"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the slice makes a new list, the loop puts each item in front, and `reverse()` changes the list itself.\n",
    "\n",
    "Problem 11. The second largest number\n",
    "\n",
    "Change it and run: change the list to `[5, 5, 5, 2]`."
   ],
   "id": "t04-258"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [12, 45, 7, 45, 38, 21]\n",
    "largest = max(numbers)\n",
    "others = list(filter(lambda n: n != largest, numbers))\n",
    "print(\"Second largest:\", max(others))"
   ],
   "id": "t04-259"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: remove every copy of the largest value with `filter`, then the largest of the rest is the answer. (Sorting and taking `[-2]` would give 45 again, because 45 appears twice.)\n",
    "\n",
    "Problem 12. Remove duplicates and keep the order"
   ],
   "id": "t04-260"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 5, 3, 8, 5, 3, 9]\n",
    "unique = []\n",
    "for number in numbers:\n",
    "    if number not in unique:\n",
    "        unique.append(number)\n",
    "print(unique)"
   ],
   "id": "t04-261"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: an item is added only if it is `not in` the new list yet.\n",
    "\n",
    "Problem 13. Squares with a loop and with `map`"
   ],
   "id": "t04-262"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5]\n",
    "\n",
    "squares = []\n",
    "for number in numbers:\n",
    "    squares.append(number ** 2)\n",
    "print(squares)\n",
    "\n",
    "print(list(map(lambda n: n ** 2, numbers)))"
   ],
   "id": "t04-263"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 14. Grades report\n",
    "\n",
    "Change it and run: type your own grades.\n",
    "\n",
    "When the cell asks for input, type `85 42 78 60 95 30`."
   ],
   "id": "t04-264"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "85 42 78 60 95 30"
     ]
    }
   },
   "outputs": [],
   "source": [
    "grades = list(map(int, input().split()))\n",
    "passed = list(filter(lambda g: g >= 50, grades))\n",
    "\n",
    "print(\"Grades:\", grades)\n",
    "print(\"Highest:\", max(grades))\n",
    "print(\"Lowest:\", min(grades))\n",
    "print(\"Average:\", round(sum(grades) / len(grades), 2))\n",
    "print(\"Passed:\", len(passed), \"of\", len(grades))"
   ],
   "id": "t04-265"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 15. Find the position of a value (linear search)\n",
    "\n",
    "Change it and run: set `target` to 100."
   ],
   "id": "t04-266"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [14, 9, 27, 3, 18]\n",
    "target = 27\n",
    "position = -1\n",
    "\n",
    "for i in range(len(numbers)):\n",
    "    if numbers[i] == target:\n",
    "        position = i\n",
    "        break\n",
    "\n",
    "if position == -1:\n",
    "    print(target, \"is not in the list\")\n",
    "else:\n",
    "    print(target, \"is at index\", position)"
   ],
   "id": "t04-267"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: we need the index, so we loop over `range(len(numbers))`, and `break` stops at the first match. (`numbers.index(27)` does the same job, but gives an error when the value is missing.)\n",
    "\n",
    "Problem 16. Count how many times each value appears"
   ],
   "id": "t04-268"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "votes = [\"yes\", \"no\", \"yes\", \"yes\", \"no\", \"maybe\"]\n",
    "seen = []\n",
    "for vote in votes:\n",
    "    if vote not in seen:\n",
    "        seen.append(vote)\n",
    "        print(vote, votes.count(vote))"
   ],
   "id": "t04-269"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 17. Celsius to Fahrenheit for a whole list"
   ],
   "id": "t04-270"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "celsius = [0, 20, 37, 100]\n",
    "fahrenheit = list(map(lambda c: c * 9 / 5 + 32, celsius))\n",
    "print(fahrenheit)\n",
    "\n",
    "for c, f in zip(celsius, fahrenheit):\n",
    "    print(c, \"C =\", f, \"F\")"
   ],
   "id": "t04-271"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 18. A function that returns two values"
   ],
   "id": "t04-272"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sum_and_average(numbers):\n",
    "    total = sum(numbers)\n",
    "    return total, total / len(numbers)\n",
    "\n",
    "total, average = sum_and_average([10, 20, 30, 40])\n",
    "print(\"Sum:\", total)\n",
    "print(\"Average:\", average)"
   ],
   "id": "t04-273"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `return total, total / len(numbers)` returns one tuple with two items, and we unpack it.\n",
    "\n",
    "Problem 19. Words of a sentence"
   ],
   "id": "t04-274"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sentence = \"python makes data science easier\"\n",
    "words = sentence.split()\n",
    "\n",
    "print(\"Words:\", len(words))\n",
    "print(\"Longest:\", max(words, key=len))\n",
    "print(\"Capitalized:\", \" \".join(map(lambda w: w.capitalize(), words)))\n",
    "print(\"Long words:\", list(filter(lambda w: len(w) > 5, words)))"
   ],
   "id": "t04-275"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 10.3 Level 3: Medium-Hard\n",
    "\n",
    "Problem 20. Merge two lists and sort the result"
   ],
   "id": "t04-276"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [5, 1, 9]\n",
    "b = [4, 8, 2]\n",
    "merged = sorted(a + b)\n",
    "print(merged)\n",
    "print(a, b)"
   ],
   "id": "t04-277"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `a + b` makes a new list and `sorted` makes a new sorted list, so `a` and `b` are unchanged.\n",
    "\n",
    "Problem 21. Split a list into positives, negatives and zeros"
   ],
   "id": "t04-278"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [4, -2, 0, 7, -9, 0, 3]\n",
    "positives = []\n",
    "negatives = []\n",
    "zeros = 0\n",
    "\n",
    "for number in numbers:\n",
    "    if number > 0:\n",
    "        positives.append(number)\n",
    "    elif number < 0:\n",
    "        negatives.append(number)\n",
    "    else:\n",
    "        zeros = zeros + 1\n",
    "\n",
    "print(\"Positive:\", positives)\n",
    "print(\"Negative:\", negatives)\n",
    "print(\"Zeros:\", zeros)"
   ],
   "id": "t04-279"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 22. Rotate a list one step to the right\n",
    "\n",
    "Change it and run: copy the two middle lines once more to rotate two steps."
   ],
   "id": "t04-280"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5]\n",
    "last = numbers.pop()\n",
    "numbers.insert(0, last)\n",
    "print(numbers)"
   ],
   "id": "t04-281"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `pop()` removes the last item and gives it back, and `insert(0, ...)` puts it in front.\n",
    "\n",
    "Problem 23. Running total\n",
    "\n",
    "Each item of the new list is the sum of all numbers so far."
   ],
   "id": "t04-282"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [5, 3, 8, 2]\n",
    "running = []\n",
    "total = 0\n",
    "for number in numbers:\n",
    "    total = total + number\n",
    "    running.append(total)\n",
    "print(running)"
   ],
   "id": "t04-283"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 24. The best student in a list of tuples"
   ],
   "id": "t04-284"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "students = [(\"Aylin\", 85), (\"Murad\", 92), (\"Leyla\", 78)]\n",
    "\n",
    "best_name = students[0][0]\n",
    "best_grade = students[0][1]\n",
    "for name, grade in students:\n",
    "    if grade > best_grade:\n",
    "        best_name = name\n",
    "        best_grade = grade\n",
    "\n",
    "print(\"Best student:\", best_name, \"with\", best_grade)"
   ],
   "id": "t04-285"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: each item is a tuple, and `for name, grade in students` unpacks it in every round.\n",
    "\n",
    "Problem 25. Sum of every row and of the whole table"
   ],
   "id": "t04-286"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "table = [\n",
    "    [1, 2, 3],\n",
    "    [4, 5, 6],\n",
    "    [7, 8, 9],\n",
    "]\n",
    "\n",
    "row_sums = list(map(sum, table))\n",
    "print(\"Row sums:\", row_sums)\n",
    "print(\"Total:\", sum(row_sums))"
   ],
   "id": "t04-287"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: every item of `table` is a list, so `map(sum, table)` runs `sum` on every row.\n",
    "\n",
    "Problem 26. Read the numbers, keep the even ones, square them, add them up\n",
    "\n",
    "Change it and run: type `10 11 12`.\n",
    "\n",
    "When the cell asks for input, type `1 2 3 4 5 6`."
   ],
   "id": "t04-288"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "1 2 3 4 5 6"
     ]
    }
   },
   "outputs": [],
   "source": [
    "numbers = list(map(int, input().split()))\n",
    "evens = list(filter(lambda n: n % 2 == 0, numbers))\n",
    "squares = list(map(lambda n: n ** 2, evens))\n",
    "\n",
    "print(\"Numbers:\", numbers)\n",
    "print(\"Even:\", evens)\n",
    "print(\"Squares:\", squares)\n",
    "print(\"Sum:\", sum(squares))"
   ],
   "id": "t04-289"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `filter` chooses, `map` changes, `sum` adds. Three small steps, each one easy to check.\n",
    "\n",
    "## 13. Quick summary\n",
    "\n",
    "| Concept | What it does | Example |\n",
    "| --- | --- | --- |\n",
    "| List | ordered, changeable collection | `[1, 2, 3]` |\n",
    "| Tuple | ordered, unchangeable collection | `(1, 2, 3)` |\n",
    "| Index | position of an item, from 0 | `items[0]`, `items[-1]` |\n",
    "| Slice | a part of the collection | `items[1:4]`, `items[::-1]` |\n",
    "| `append` / `insert` / `extend` | add items to a list | `items.append(5)` |\n",
    "| `remove` / `pop` / `del` / `clear` | remove items from a list | `items.pop()` |\n",
    "| `index` / `count` / `in` | search | `items.count(3)` |\n",
    "| `sort` / `sorted` / `reverse` | order | `sorted(items)` |\n",
    "| `copy` | a separate copy of a list | `b = a.copy()` |\n",
    "| `len` / `sum` / `min` / `max` | calculate | `sum(items) / len(items)` |\n",
    "| `for item in items` | go through the items | loop + `if` |\n",
    "| `enumerate` | index and item together | `for i, x in enumerate(items):` |\n",
    "| Unpacking | values into variables | `a, b = (1, 2)` |\n",
    "| `split` / `join` | text to list / list to text | `\"a b\".split()` |\n",
    "| Read two numbers | one line of input | `a, b = map(int, input().split())` |\n",
    "| Read a list | one line of input | `list(map(int, input().split()))` |\n",
    "| `map` | changes every item | `map(lambda n: n * 2, items)` |\n",
    "| `filter` | keeps some items | `filter(lambda n: n > 0, items)` |\n",
    "| `lambda` | a small function in one line | `lambda n: n * 2` |\n",
    "\n",
    "Golden rules\n",
    "\n",
    "1. Indexes start at 0, and the last item is `[-1]`.\n",
    "2. A list can change, a tuple cannot. If you are not sure, use a list.\n",
    "3. Methods that change a list return `None`: never write `a = a.sort()` or `a = a.append(x)`.\n",
    "4. `b = a` is not a copy. Use `a.copy()`.\n",
    "5. Do not remove items from a list while looping over it. Build a new list.\n",
    "6. `map` changes every item, `filter` chooses items. Wrap both in `list()`.\n",
    "7. `input().split()` gives text. Use `map(int, ...)` to get numbers.\n",
    "8. `(5,)` is a tuple, `(5)` is a number.\n",
    "\n",
    "Next: the practice notebook (topic-04-practice.ipynb), then Topic 5: dictionaries, sets and comprehensions."
   ],
   "id": "t04-290"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
