{ "cells": [ { "cell_type": "markdown", "id": "cd9bf0ba", "metadata": {}, "source": [ "--- \n", " \n", "\n", "

Department of Data Science

\n", "

Course: Tools and Techniques for Data Science

\n", "\n", "---\n", "

Instructor: Muhammad Arif Butt, Ph.D.

" ] }, { "cell_type": "markdown", "id": "14003b31", "metadata": {}, "source": [ "

Lecture 2.10

" ] }, { "cell_type": "markdown", "id": "6db50786", "metadata": {}, "source": [ "\"Open" ] }, { "cell_type": "markdown", "id": "f90308da", "metadata": {}, "source": [ "## _loops.ipynb_" ] }, { "cell_type": "markdown", "id": "fa7840eb", "metadata": {}, "source": [ "## Learning agenda of this notebook\n", "There are scenarios is programming, where we need to repeat a set of instructions a specified number of times or until a condition is met. This is called iteration. A programming structure that implements iteration is called a loop. In programming there are two types of iteration:\n", "1. Indefinite Iteration, implemented using a `while` loop\n", " - Basic `while` loop examples\n", " - Use of `break`, `continue` and `else` in `while` loop \n", " - Nested `while` loop

\n", "3. Definite Iteration, implemented using a `for` loop\n", " - Iterables and Iterators\n", " - Basic `for` loop examples\n", " - The `range()` and `enumerate()` functions\n", " - Use of `break`, `continue` and `else` in `for` loop\n", " - Nested `for` loop

\n", "4. List Comprehension

\n", "5. Dictionary Comprehension" ] }, { "cell_type": "markdown", "id": "efe70ed5", "metadata": {}, "source": [ " \n", "\n", "## 1. The `while` Loop\n", "```\n", "initialize loop variable\n", "while (condition is true):\n", " statement(s)\n", " update loop variable\n", "statement(s)\n", "```\n", "- The indented block of code, often refered to as body of the loop will be executed repeatedly until the condition/expression evaluates to False.\n", "- The condition or controlling expression, typically involves on or more variables that are initialized prior to starting the loop and then modified somewhere in the loop body.\n", "- While loop is generally used, when we don't know the number of times to iterate beforehand." ] }, { "cell_type": "code", "execution_count": 1, "id": "681def34", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The \"while\" statement\n", "*********************\n", "\n", "The \"while\" statement is used for repeated execution as long as an\n", "expression is true:\n", "\n", " while_stmt ::= \"while\" assignment_expression \":\" suite\n", " [\"else\" \":\" suite]\n", "\n", "This repeatedly tests the expression and, if it is true, executes the\n", "first suite; if the expression is false (which may be the first time\n", "it is tested) the suite of the \"else\" clause, if present, is executed\n", "and the loop terminates.\n", "\n", "A \"break\" statement executed in the first suite terminates the loop\n", "without executing the \"else\" clause’s suite. A \"continue\" statement\n", "executed in the first suite skips the rest of the suite and goes back\n", "to testing the expression.\n", "\n", "Related help topics: break, continue, if, TRUTHVALUE\n", "\n" ] } ], "source": [ "help('while')" ] }, { "cell_type": "markdown", "id": "629f773e", "metadata": {}, "source": [ "### a. Basics of While Loop" ] }, { "cell_type": "code", "execution_count": 2, "id": "7d1a532b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "Bye-Bye\n" ] } ], "source": [ "# Example 1: Print numbers\n", "# initialize loop variable - check condition - update loop variable\n", "number = 0\n", "while number < 7:\n", " print(number)\n", " number = number + 1\n", "print(\"Bye-Bye\")" ] }, { "cell_type": "code", "execution_count": 3, "id": "1f0ddd4e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000\n", "CPU times: user 474 µs, sys: 429 µs, total: 903 µs\n", "Wall time: 543 µs\n" ] } ], "source": [ "%%time \n", "# Example 2: Calculate 100th factorial\n", "i = 1 \n", "result = 1\n", "if i == 0:\n", " result = 1\n", "else:\n", " while (i <= 100):\n", " result = result * i\n", " i += 1\n", "print(result)" ] }, { "cell_type": "markdown", "id": "0b09e2d3", "metadata": {}, "source": [ "User time is the amount of CPU time taken outside of the kernel. Sys time is the amount of time taken inside of the kernel, and Wall time the time the code was submitted to the CPU to the time when the process completed." ] }, { "cell_type": "markdown", "id": "1a39c34f", "metadata": {}, "source": [ "Here's how the above code works:\n", "\n", "* We initialize two variables, `result` and, `i`. `result` will contain the final outcome. And `i` is used to keep track of the next number to be multiplied with `result`. Both are initialized to 1 (can you explain why?)\n", "\n", "* The condition `i <= 100` holds true (since `i` is initially `1`), so the `while` block is executed.\n", "\n", "* The `result` is updated to `result * i`, `i` is increased by `1` and it now has the value `2`.\n", "\n", "* At this point, the condition `i <= 100` is evaluated again. Since it continues to hold true, `result` is again updated to `result * i`, and `i` is increased to `3`.\n", "\n", "* This process is repeated till the condition becomes false, which happens when `i` holds the value `101`. Once the condition evaluates to `False`, the execution of the loop ends, and the `print` statement below it is executed. \n" ] }, { "cell_type": "code", "execution_count": 4, "id": "edd4a13e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter number: 6\n", "The sum is 21\n" ] } ], "source": [ "# Example 3: Input number from user and compute the sum 1+2+3+4+....+n\n", "n = int(input(\"Enter number: \"))\n", "sum = 0\n", "i = 1\n", "while (i <= n):\n", " sum = sum + i\n", " i = i+1 # update counter\n", "print(\"The sum is\", sum)" ] }, { "cell_type": "code", "execution_count": 5, "id": "324c5616", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Learning\n", "is\n", "fun\n", "with\n", "Arif Butt\n", "['Learning', 'is', 'fun', 'with', 'Arif Butt']\n" ] } ], "source": [ "# # Example 4: while loop iterates over the elements until a certain condition is met\n", "list1 = ['Learning', 'is', 'fun', 'with', 'Arif Butt']\n", "ctr = 0\n", "while(ctr < len(list1)):\n", " print(list1[ctr])\n", " ctr += 1\n", "\n", "print(list1)" ] }, { "cell_type": "code", "execution_count": 6, "id": "49751c6d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "mylist before the loop: ['Arif', 'Hadeed', 'Mujahid', 'Maaz']\n", "This is iteration number: 1\n", "This is iteration number: 2\n", "This is iteration number: 3\n", "This is iteration number: 4\n", "mylist after the loop: []\n" ] } ], "source": [ "# Example 5: Using iterables inside a while loop expression\n", "mylist = ['Arif', 'Hadeed','Mujahid', 'Maaz']\n", "print(\"mylist before the loop: \", mylist)\n", "\n", "x = 1\n", "while mylist: #you read it as while there exist elements in the iterable mylist do following\n", " print(\"This is iteration number: \", x)\n", " x += 1\n", " mylist.pop() # removes the right most value from the iterable mylist each time it is called\n", " \n", "print(\"mylist after the loop: \",mylist)" ] }, { "cell_type": "code", "execution_count": null, "id": "19918cb9", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 7, "id": "20b80627", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter count of fibonacci numbers you want to print: 9\n", "Required Fibonacci series: [0, 1, 1, 2, 3, 5, 8, 13, 21]\n" ] } ], "source": [ "# Example 6: Print Fibonacci series\n", "n = int(input(\"Enter count of fibonacci numbers you want to print: \"))\n", "i = 1\n", "if n<1:\n", " fib = [] # In case user enter <0, the list is empty\n", "elif n==1:\n", " fib = [0] # If user enters 1, the list has the first fibonacci number\n", "elif n==2:\n", " fib = [0, 1] # If user enters 2, the list has the first two fibonacci numbers\n", "elif n > 2:\n", " fib = [0, 1] # if n>2, then we need to enter in while loop to compute the rest of the fibonacci numbers\n", " while (i < n-1):\n", " fib.append(fib[i] + fib[i-1])\n", " i += 1\n", "print(\"Required Fibonacci series: \", fib)" ] }, { "cell_type": "markdown", "id": "532a3dcb", "metadata": {}, "source": [ "### b. Nested While Loops\n", "- A while loop can have other control structures such as `if` statements or other `while` loops nested under them" ] }, { "cell_type": "code", "execution_count": 8, "id": "406b22a3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Outer: 5\n", "\t Inner: Rauf\n", "\t Inner: Arif\n", "Outer: 4\n", "\t Inner: Rauf\n", "\t Inner: Arif\n", "Outer: 3\n", "\t Inner: Rauf\n", "\t Inner: Arif\n", "Outer: 2\n", "\t Inner: Rauf\n", "\t Inner: Arif\n", "Outer: 1\n", "\t Inner: Rauf\n", "\t Inner: Arif\n", "After both the loops end\n", "a= []\n", "b= []\n" ] } ], "source": [ "# Example 1: A while loop nested inside another while loop\n", "# Note the inner while loop works on a list that is declared again and again inside the outer loop\n", "a = [1,2,3,4,5]\n", "while (a):\n", " print(\"Outer: \", a.pop())\n", " b = ['Arif', 'Rauf']\n", " while (b):\n", " print(\"\\t Inner: \", b.pop())\n", "\n", "print(\"After both the loops end\")\n", "print(\"a= \", a)\n", "print(\"b= \", b)" ] }, { "cell_type": "code", "execution_count": null, "id": "cf302ca1", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "566a05d1", "metadata": {}, "source": [ "## 2. Jump Statements in Python (`break` and `continue`)\n", "\n", " \n", "\n", " \n", "\n", "In the above examples, we have seen that the entire body of the while loop is executed on each iteration. Python provides two keywords that terminate a loop iteration prematurely:\n", "- Python **`break`** statement immediately terminates a loop entirely. Program execution proceeds to the first statement after the loop body.

\n", "- Python **`continue`** statement immediately terminates the current loop iteration. Program execution jumps to the top of the loop, and the loop condition is re-evaluated to determine whether the loop will execute again or terminate\n", " " ] }, { "cell_type": "markdown", "id": "73c2c76b", "metadata": {}, "source": [ "### a. Infinite loop and break statement: " ] }, { "cell_type": "code", "execution_count": 9, "id": "4fe24e36", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The \"break\" statement\n", "*********************\n", "\n", " break_stmt ::= \"break\"\n", "\n", "\"break\" may only occur syntactically nested in a \"for\" or \"while\"\n", "loop, but not nested in a function or class definition within that\n", "loop.\n", "\n", "It terminates the nearest enclosing loop, skipping the optional \"else\"\n", "clause if the loop has one.\n", "\n", "If a \"for\" loop is terminated by \"break\", the loop control target\n", "keeps its current value.\n", "\n", "When \"break\" passes control out of a \"try\" statement with a \"finally\"\n", "clause, that \"finally\" clause is executed before really leaving the\n", "loop.\n", "\n", "Related help topics: while, for\n", "\n" ] } ], "source": [ "help('break')" ] }, { "cell_type": "code", "execution_count": 10, "id": "f4957e8f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "Outside loop\n" ] } ], "source": [ "#Example 1: Breaking an infinite while loop on a certain condition\n", "n = 0\n", "while (True):\n", " n = n + 1\n", " if (n == 5):\n", " break\n", " print(n)\n", "print(\"Outside loop\")" ] }, { "cell_type": "code", "execution_count": 11, "id": "de092cb7", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9\n", "8\n", "7\n", "6\n" ] } ], "source": [ "#Example 2: Breaking a while loop on a certain condition\n", "n = 10\n", "while (n > 0):\n", " n = n - 1\n", " if (n == 5):\n", " break\n", " print(n)" ] }, { "cell_type": "markdown", "id": "27079c95", "metadata": {}, "source": [ "### b. The `continue` statement: \n", "- Python **continue** statement immediately terminates the current loop iteration. Program execution jumps to the top of the loop, and the loop condition is re-evaluated to determine whether the loop will execute again or terminate" ] }, { "cell_type": "code", "execution_count": 12, "id": "3dbe280d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The \"continue\" statement\n", "************************\n", "\n", " continue_stmt ::= \"continue\"\n", "\n", "\"continue\" may only occur syntactically nested in a \"for\" or \"while\"\n", "loop, but not nested in a function or class definition within that\n", "loop. It continues with the next cycle of the nearest enclosing loop.\n", "\n", "When \"continue\" passes control out of a \"try\" statement with a\n", "\"finally\" clause, that \"finally\" clause is executed before really\n", "starting the next loop cycle.\n", "\n", "Related help topics: while, for\n", "\n" ] } ], "source": [ "help('continue')" ] }, { "cell_type": "code", "execution_count": 13, "id": "7fe06b75", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9\n", "8\n", "6\n", "4\n", "3\n", "2\n", "1\n", "0\n" ] } ], "source": [ "#Example 1: Use of continue\n", "n = 10\n", "while n > 0:\n", " n = n - 1\n", " if (n == 5 or n == 7):\n", " continue\n", " print(n)" ] }, { "cell_type": "code", "execution_count": 14, "id": "6a6fc549", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9\n", "7\n", "5\n", "3\n", "1\n" ] } ], "source": [ "#Example 2: Use of continue\n", "n = 10\n", "while n > 0:\n", " n = n - 1\n", " if (n % 2 == 0):\n", " continue\n", " print(n)" ] }, { "cell_type": "markdown", "id": "e35ee7fa", "metadata": {}, "source": [ "### c. The `while` loop with `else` statement: \n", "- On normal termination of loop, i.e., when the loop condition becomes False, the `else` clause will execute. \n", "- However, if the loop is terminated prematurely by either a break or return statement, the `else` clause won’t execute at all." ] }, { "cell_type": "code", "execution_count": 15, "id": "34c87a59", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "3\n", "2\n", "1\n", "0\n", "Loop is finished\n", "outside loop\n" ] } ], "source": [ "# Example: The `else` block will execute only when the loop condition becomes false\n", "n = 5\n", "while n > 0:\n", " n = n - 1\n", " print(n)\n", "else:\n", " print(\"Loop is finished\")\n", "print(\"outside loop\")" ] }, { "cell_type": "code", "execution_count": 16, "id": "c30a79e8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "3\n", "2\n", "1\n", "0\n", "Loop is finished\n", "outside loop\n" ] } ], "source": [ "n = 5\n", "while n > 0:\n", " n = n - 1\n", " print(n)\n", "print(\"Loop is finished\")\n", "print(\"outside loop\")" ] }, { "cell_type": "code", "execution_count": 17, "id": "be892815", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "3\n", "outside loop\n" ] } ], "source": [ "# Example: The `else` block will NOT execute because the loop breaks w/o the loop condition being false\n", "n = 5\n", "while n > 0:\n", " n = n - 1\n", " if (n==2):\n", " break\n", " print(n)\n", "else:\n", " print(\"Loop is finished\")\n", "print(\"outside loop\")" ] }, { "cell_type": "markdown", "id": "e0aa81c0", "metadata": {}, "source": [ " \n", "\n", "## 3. The `for` Loop\n", "- We use `for` loop when we want to run a block of code for known set of items in an iterable.\n", "- In the context of most data science work, Python `for` loops are used to loop through an iterable object (like a list, tuple, set, dictionary) and perform the same action for each entry. \n", "- For example, a for loop would allow us to iterate through a list, performing the same action on each item in the list.\n", "```\n", "for variable in :\n", " \n", "```\n", "- Before we see a basic example of a Python `for` loop, let us first understand the concept of **Iterables** and **Iterators**" ] }, { "cell_type": "markdown", "id": "702a0369", "metadata": {}, "source": [ "### a. Iterables and Iterators\n", "- An `Iterable` in Python is an object that is capable of returning its members one at a time, and therefore, can be used in an iteration. Lists, Tuples, Sets and Dictionaries are iterables.\n", "- An `Iterator` in Python is an object that is used to iterate over iterable objects\n", " - To initialize an iterator we pass an iterable object to Python built-in function `iter()`\n", " - The `iter()` function returns an iterator for that iterable object. \n", " - Later we use the Python built-in `next()` function to iterate over the elements of that iterable\n", "- Let us understand this using some example codes:" ] }, { "cell_type": "markdown", "id": "db962e64", "metadata": {}, "source": [ "#### The `iter()` function" ] }, { "cell_type": "code", "execution_count": 18, "id": "bd3f04ce", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function iter in module builtins:\n", "\n", "iter(...)\n", " iter(iterable) -> iterator\n", " iter(callable, sentinel) -> iterator\n", " \n", " Get an iterator from an object. In the first form, the argument must\n", " supply its own iterator, or be a sequence.\n", " In the second form, the callable is called until it returns the sentinel.\n", "\n" ] } ], "source": [ "help(iter)" ] }, { "cell_type": "code", "execution_count": 19, "id": "62ad3406", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Creating list iterator from a list iterable using the iter() method\n", "mylist = ['banana', 'mango', 'grapes']\n", "iterator_mylist = iter(mylist)\n", "iterator_mylist" ] }, { "cell_type": "code", "execution_count": 20, "id": "d69ffb74", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Creating tuple iterator from a tuple iterable using the iter() method\n", "mytuple = ('banana', 'mango', 'grapes')\n", "iterator_mytuple = iter(mytuple)\n", "iterator_mytuple" ] }, { "cell_type": "code", "execution_count": 21, "id": "472b6218", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Creating set iterator from a set iterable using the iter() method\n", "myset = set(['banana', 'mango', 'grapes'])\n", "iterator_myset = iter(myset)\n", "iterator_myset" ] }, { "cell_type": "code", "execution_count": 22, "id": "6faac3ee", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Creating dictionary key-iterator from a dictionary iterable using the iter() method\n", "mydict = {1:'banana', 2:'mango', 3:'grapes'}\n", "iterator_dictkeys = iter(mydict)\n", "iterator_dictkeys" ] }, { "cell_type": "code", "execution_count": 23, "id": "cba9285e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Creating dictionary key-iterator from a dictionary iterable using the iter() method\n", "mydict = {1:'banana', 2:'mango', 3:'grapes'}\n", "iterator_dictkeys = iter(mydict.keys())\n", "iterator_dictkeys" ] }, { "cell_type": "code", "execution_count": 24, "id": "7b0488d4", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Creating dictionary value-iterator from a dictionary iterable using the iter() method\n", "mydict = {1:'banana', 2:'mango', 3:'grapes'}\n", "iterator_dictvals = iter(mydict.values())\n", "iterator_dictvals" ] }, { "cell_type": "code", "execution_count": 25, "id": "f732a819", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Creating dictionary item-iterator from a dictionary iterable using the iter() method\n", "mydict = {1:'banana', 2:'mango', 3:'grapes'}\n", "iterator_dictitems = iter(mydict.items())\n", "iterator_dictitems" ] }, { "cell_type": "markdown", "id": "198ae9ba", "metadata": {}, "source": [ "#### The `next()` function" ] }, { "cell_type": "markdown", "id": "96d8a6c1", "metadata": {}, "source": [ "- The Python built-in `next()` function is passed the iterator of the iterable object returned by the `iter()` function\n", "- Every time `next()` is called it return the next item from its associated iterable object\n", "- The `next()` function keeps moving from item to item in the iterator" ] }, { "cell_type": "code", "execution_count": 26, "id": "5c2952e0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function next in module builtins:\n", "\n", "next(...)\n", " next(iterator[, default])\n", " \n", " Return the next item from the iterator. If default is given and the iterator\n", " is exhausted, it is returned instead of raising StopIteration.\n", "\n" ] } ], "source": [ "help(next)" ] }, { "cell_type": "code", "execution_count": 27, "id": "8580ff2d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "banana\n", "mango\n", "grapes\n" ] } ], "source": [ "# The iter() method yields successive values from an iterable object, if called successively\n", "mylist = ['banana', 'mango', 'grapes']\n", "a = iter(mylist)\n", "print(next(a))\n", "print(next(a))\n", "print(next(a))" ] }, { "cell_type": "code", "execution_count": 28, "id": "f479b739", "metadata": {}, "outputs": [ { "ename": "StopIteration", "evalue": "", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mStopIteration\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_28205/209159179.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Once you are exhausted with all the values in the iterator, you get stop Iteration error\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mStopIteration\u001b[0m: " ] } ], "source": [ "# Once you are exhausted with all the values in the iterator, you get stop Iteration error\n", "next(a)" ] }, { "cell_type": "markdown", "id": "c9c22c22", "metadata": {}, "source": [ ">**So the `iter()` and the `next()` functions makes the basis of a `for` loop in Python**" ] }, { "cell_type": "markdown", "id": "bd6bcfbc", "metadata": {}, "source": [ "### b. Basic For Loop Examples" ] }, { "cell_type": "code", "execution_count": 29, "id": "4a7feeee", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Arif\n", "Hadeed\n", "Muhahid\n", "Elements of mylist exhausted and next() returned StopIteration Error, which is handled by for loop\n" ] } ], "source": [ "# Example 1\n", "mylist = ['Arif', 'Hadeed', 'Muhahid']\n", "\n", "for i in mylist:\n", " print(i)\n", "print(\"Elements of mylist exhausted and next() returned StopIteration Error, which is handled by for loop\")" ] }, { "cell_type": "markdown", "id": "609618d8", "metadata": {}, "source": [ "- Let us see behind the curtain (How the above for loop works):\n", " - Calls `iter()` to obtain an iterator for mylist\n", " - Calls `next()` repeatedly to obtain items from the iterator object\n", " - Terminate the for loop when `next()` raises a StopIteration exception" ] }, { "cell_type": "code", "execution_count": 30, "id": "24f52411", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "B\n", "e\n", " \n", "H\n", "a\n", "p\n", "p\n", "y\n" ] } ], "source": [ "# Example 2: Loop through the letters in a string\n", "for i in (\"Be Happy\"):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 31, "id": "8cef87e4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "arif\n", "rauf\n", "hadeed\n", "zalaid\n" ] } ], "source": [ "# Example 3: Iterate a tuple using for loop\n", "friends = ('arif', 'rauf', 'hadeed', 'zalaid')\n", "\n", "for friend in friends:\n", " print(friend)" ] }, { "cell_type": "code", "execution_count": 32, "id": "1c882526", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n" ] } ], "source": [ "# Example 4: Iterate a string using for loop and count the count of a specific character\n", "word = \"Welcome to Learning with Arif Butt.\"\n", "count = 0\n", "for character in word:\n", " if character == 'i':\n", " count = count+1\n", "print(count)" ] }, { "cell_type": "code", "execution_count": 33, "id": "e3a1de2d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Iterating through dictionary keys:\n", "Name\n", "Gender\n", "Age\n", "Height\n", "Occupation\n", "Another way of iterating through dictionary keys:\n", "Name\n", "Gender\n", "Age\n", "Height\n", "Occupation\n" ] } ], "source": [ "# Example 5: Iterating through a dictionary keys\n", "d1 = {\n", " 'Name': 'Kakamanna', \n", " 'Gender': 'Male', \n", " 'Age': 23, \n", " 'Height': 6.1, \n", " 'Occupation': 'Student'\n", "}\n", "print(\"Iterating through dictionary keys:\")\n", "for i in d1:\n", " print(i)\n", " \n", "print(\"Another way of iterating through dictionary keys:\")\n", "for i in d1.keys():\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 34, "id": "cbfc78f6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Iterating through a dictionary values:\n", "Kakamanna\n", "Male\n", "23\n", "6.1\n", "Student\n" ] } ], "source": [ "# Example 6: Iterating through the values\n", "d1 = {\n", " 'Name': 'Kakamanna', \n", " 'Gender': 'Male', \n", " 'Age': 23, \n", " 'Height': 6.1, \n", " 'Occupation': 'Student'\n", "}\n", "print(\"Iterating through a dictionary values:\")\n", "for i in d1.values():\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 35, "id": "7613efba", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Iterating through a dictionary key:value pairs:\n", "('Name', 'Kakamanna')\n", "('Gender', 'Male')\n", "('Age', 23)\n", "('Height', 6.1)\n", "('Occupation', 'Student')\n" ] } ], "source": [ "# Example 7: Iterating through the key-value pairs\n", "d1 = {\n", " 'Name': 'Kakamanna', \n", " 'Gender': 'Male', \n", " 'Age': 23, \n", " 'Height': 6.1, \n", " 'Occupation': 'Student'\n", "}\n", "print(\"\\nIterating through a dictionary key:value pairs:\")\n", "for i in d1.items():\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 36, "id": "fa38f10f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Iterating through a dictionary key:value pairs:\n", "Name Kakamanna\n", "Gender Male\n", "Age 23\n", "Height 6.1\n", "Occupation Student\n" ] } ], "source": [ "d1 = {\n", " 'Name': 'Kakamanna', \n", " 'Gender': 'Male', \n", " 'Age': 23, \n", " 'Height': 6.1, \n", " 'Occupation': 'Student'\n", "}\n", "print(\"\\nIterating through a dictionary key:value pairs:\")\n", "for k,v in d1.items():\n", " print(k,v)" ] }, { "cell_type": "markdown", "id": "fabae812", "metadata": {}, "source": [ "#### The `pass` statement in a `for` loop\n", "- The `pass` statement is generally used as a placeholder i.e. when the user does not know what code to write. \n", "- So user can simply write `pass` statement, where empty code is not allowed, like in loops, function definitions, class definitions, or in if statements." ] }, { "cell_type": "code", "execution_count": 37, "id": "6a4716ad", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The \"pass\" statement\n", "********************\n", "\n", " pass_stmt ::= \"pass\"\n", "\n", "\"pass\" is a null operation — when it is executed, nothing happens. It\n", "is useful as a placeholder when a statement is required syntactically,\n", "but no code needs to be executed, for example:\n", "\n", " def f(arg): pass # a function that does nothing (yet)\n", "\n", " class C: pass # a class with no methods (yet)\n", "\n" ] } ], "source": [ "help('pass')" ] }, { "cell_type": "code", "execution_count": 38, "id": "55bdd06b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "rauf\n", "hadeed\n", "mujahid\n" ] } ], "source": [ "# Print all elements of list ignoring string \"arif\"\n", "list1 =['rauf', 'arif', 'hadeed', 'mujahid']\n", " \n", "for i in list1:\n", " if(i =='arif'):\n", " pass # do nothing \n", " else:\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 39, "id": "ac1cd03d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Thisisgreatstuff" ] } ], "source": [ "# Print the string ignoring spaces\n", "str1 = \"This is great stuff\"\n", "for i in str1:\n", " if(i ==' '):\n", " pass\n", " else:\n", " print(i, end=\"\")" ] }, { "cell_type": "markdown", "id": "3deb901c", "metadata": {}, "source": [ "### c. Using `range()` Function in `for` Loops\n", "- The `range()` method is used to create a range object, containing sequence of numbers that can be iterated over using a `for` loop.\n", "- It can be used in 3 ways:\n", "* `range(n)` - Creates a sequence of numbers from `0` to `n-1`\n", "* `range(a, b)` - Creates a sequence of numbers from `a` to `b-1`\n", "* `range(a, b, step)` - Creates a sequence of numbers from `a` to `b-1` with increment/decrement of `step`" ] }, { "cell_type": "code", "execution_count": 26, "id": "cd4c09ef", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class range in module builtins:\n", "\n", "class range(object)\n", " | range(stop) -> range object\n", " | range(start, stop[, step]) -> range object\n", " | \n", " | Return an object that produces a sequence of integers from start (inclusive)\n", " | to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.\n", " | start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.\n", " | These are exactly the valid indices for a list of 4 elements.\n", " | When step is given, it specifies the increment (or decrement).\n", " | \n", " | Methods defined here:\n", " | \n", " | __bool__(self, /)\n", " | self != 0\n", " | \n", " | __contains__(self, key, /)\n", " | Return key in self.\n", " | \n", " | __eq__(self, value, /)\n", " | Return self==value.\n", " | \n", " | __ge__(self, value, /)\n", " | Return self>=value.\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | __getitem__(self, key, /)\n", " | Return self[key].\n", " | \n", " | __gt__(self, value, /)\n", " | Return self>value.\n", " | \n", " | __hash__(self, /)\n", " | Return hash(self).\n", " | \n", " | __iter__(self, /)\n", " | Implement iter(self).\n", " | \n", " | __le__(self, value, /)\n", " | Return self<=value.\n", " | \n", " | __len__(self, /)\n", " | Return len(self).\n", " | \n", " | __lt__(self, value, /)\n", " | Return self integer -- return number of occurrences of value\n", " | \n", " | index(...)\n", " | rangeobject.index(value) -> integer -- return index of value.\n", " | Raise ValueError if the value is not present.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods defined here:\n", " | \n", " | __new__(*args, **kwargs) from builtins.type\n", " | Create and return a new object. See help(type) for accurate signature.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | start\n", " | \n", " | step\n", " | \n", " | stop\n", "\n" ] } ], "source": [ "help(range)" ] }, { "cell_type": "code", "execution_count": 40, "id": "19c0cf34", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "rv = range(10)\n", "print(type(rv))" ] }, { "cell_type": "code", "execution_count": 41, "id": "b8f751ce", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "range(0, 10)\n", "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "[-5, -4, -3, -2, -1, 0, 1]\n", "[20, 17, 14, 11, 8, 5]\n" ] } ], "source": [ "print(range(10)) # returns an iterator object containing integer values\n", "\n", "print(list(range(10)))\n", "\n", "print(list(range(-5, 2, 1)))\n", "\n", "print(list(range(20, 2, -3)))" ] }, { "cell_type": "code", "execution_count": 42, "id": "870b49ca", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "#Example 1: \n", "a = range(5) \n", "for i in a:\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 43, "id": "2cde61b3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "source": [ "#Example 2:\n", "#a = range(3, 10) \n", "for i in range(3, 10):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 44, "id": "6425ef11", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "7\n", "11\n" ] } ], "source": [ "#Example 3: \n", "a = range(3, 15, 4) \n", "for i in a:\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 45, "id": "2cb6749c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The value at position 0 is Rauf.\n", "The value at position 1 is Arif.\n", "The value at position 2 is Maaz.\n", "The value at position 3 is Hadeed.\n", "The value at position 4 is Muhahid.\n", "The value at position 5 is Mohid.\n" ] } ], "source": [ "# Example 4: Used to iterate over Lists, when you need to track the index of elements while iterating.\n", "friends = ['Rauf','Arif', 'Maaz', 'Hadeed', 'Muhahid', 'Mohid']\n", "\n", "for i in range(len(friends)): # Remember the len() function returns 6 in this scenario\n", " print('The value at position {} is {}.'.format(i, friends[i]))" ] }, { "cell_type": "markdown", "id": "b094a17d", "metadata": {}, "source": [ "### d. Using `enumerate()` Function in `for` Loops\n", "- The `enumerate()` method is passed an iterable object and returns an enumerate object containing tuples, each tuple having two values:\n", "```\n", "(index, data_at_that_index_in_the_iterable)\n", "```\n", "- It is is useful for obtaining an indexed list:\n", "```\n", " (0, seq[0]), (1, seq[1]), (2, seq[2]), ...\n", "```" ] }, { "cell_type": "code", "execution_count": 46, "id": "d43f0fc0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "mylist = ['arif', 'hadeed', 'mujahid']\n", "rv = enumerate(mylist)\n", "print(type(rv))" ] }, { "cell_type": "code", "execution_count": 47, "id": "15d86b41", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(0, 'arif'), (1, 'hadeed'), (2, 'mujahid')]\n" ] } ], "source": [ "mylist = ['arif', 'hadeed', 'mujahid']\n", "print(list(enumerate(mylist)))" ] }, { "cell_type": "code", "execution_count": 48, "id": "f72b4688", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{0: 'arif', 1: 'hadeed', 2: 'mujahid'}\n" ] } ], "source": [ "mylist = ['arif', 'hadeed', 'mujahid']\n", "print(dict(enumerate(mylist)))" ] }, { "cell_type": "code", "execution_count": 49, "id": "d8043e82", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The value at position 0 is Rauf.\n", "The value at position 1 is Arif.\n", "The value at position 2 is Maaz.\n", "The value at position 3 is Hadeed.\n", "The value at position 4 is Muhahid.\n", "The value at position 5 is Mohid.\n" ] } ], "source": [ "friends = ['Rauf', 'Arif', 'Maaz', 'Hadeed', 'Muhahid', 'Mohid']\n", "\n", "for i, name in enumerate(friends): \n", " print('The value at position {} is {}.'.format(i, friends[i]))" ] }, { "cell_type": "markdown", "id": "96fb967a", "metadata": {}, "source": [ "### d. Use of `break` and `continue` statement inside a `for` loop\n", "- Python **break** statement immediately terminates a loop entirely. Program execution proceeds to the first statement after the loop body.\n", "- Python **continue** statement immediately terminates the current loop iteration. Program execution jumps to the top of the loop, and the loop condition is re-evaluated to determine whether the loop will execute again or terminate" ] }, { "cell_type": "code", "execution_count": 50, "id": "0673d9d3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple\n", "banana\n" ] } ], "source": [ "# Example 1: Break the loop when it reaches the element \"cherry\"\n", "fruits = [\"apple\", \"banana\", \"cherry\", \"guava\"]\n", "for x in fruits:\n", " if x == \"cherry\":\n", " break\n", " print(x)" ] }, { "cell_type": "code", "execution_count": 51, "id": "56645937", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple\n", "cherry\n", "guava\n" ] } ], "source": [ "# Example 2: Do not print banana from the list\n", "fruits = [\"apple\", \"banana\", \"cherry\", \"guava\"]\n", "for x in fruits:\n", " if x == \"banana\":\n", " continue\n", " print(x)" ] }, { "cell_type": "code", "execution_count": 52, "id": "1f71aa58", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "3\n", "5\n", "7\n", "9\n", "11\n" ] } ], "source": [ "# Example 3: Print odd numbers from 1 to 11\n", "for i in range(1,12):\n", " if i%2 == 0:\n", " continue\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 54, "id": "78392ef5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "enter name: arif\n", "90\n", "Outside loop\n" ] } ], "source": [ "# Example 4: A for loop with else and break\n", "mydict = {\n", " 'arif':90, \n", " 'rauf':95, \n", " 'maaz':81, \n", " 'hadeed':77, \n", " 'mujahid':86, \n", " 'mohid':100\n", " }\n", "\n", "student_name = input('enter name: ')\n", "for name in mydict.keys():\n", " if name == student_name:\n", " print(mydict[name])\n", " break\n", "else:\n", " print('No entry with that name found.')\n", "print(\"Outside loop\")" ] }, { "cell_type": "markdown", "id": "eb71393a", "metadata": {}, "source": [ "### e. Nested for loop" ] }, { "cell_type": "code", "execution_count": 55, "id": "cf9b091b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Outer: 1\n", "\t Inner: Arif\n", "\t Inner: Rauf\n", "Outer: 2\n", "\t Inner: Arif\n", "\t Inner: Rauf\n", "Outer: 3\n", "\t Inner: Arif\n", "\t Inner: Rauf\n", "Outer: 4\n", "\t Inner: Arif\n", "\t Inner: Rauf\n", "Outside loops\n" ] } ], "source": [ "# Example: A for loop nested inside another for loop\n", "# Note the inner for loop works on a list that is declared again and again inside the outer loop\n", "list1 = [1,2,3,4]\n", "for numb in list1:\n", " print(\"Outer: \", numb)\n", " list2 = ['Arif', 'Rauf']\n", " for name in list2:\n", " print(\"\\t Inner: \", name)\n", "\n", "print(\"Outside loops\")" ] }, { "cell_type": "code", "execution_count": 56, "id": "a255cd2b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Monday apple\n", "Monday banana\n", "Monday guava\n", "Tuesday apple\n", "Tuesday banana\n", "Tuesday guava\n", "Wednesday apple\n", "Wednesday banana\n", "Wednesday guava\n" ] } ], "source": [ "days = ['Monday', 'Tuesday', 'Wednesday']\n", "fruits = ['apple', 'banana', 'guava']\n", "\n", "for day in days:\n", " for fruit in fruits:\n", " print(day, fruit)" ] }, { "cell_type": "code", "execution_count": null, "id": "d051df7e", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "27e28f73", "metadata": {}, "source": [ "## 4. List Comprehension\n", "- In Python comprehension is a concise way to create a new sequence based on the values of an existing sequence (which can be a list, dictionary, set or a generator)\n", "- Let us understand List comprehension step by step with examples:" ] }, { "cell_type": "markdown", "id": "f9c3ba8c", "metadata": {}, "source": [ "**Example 1:** Suppose we have an oldlist containing some random numbers. We want to create a new list that contains square of the numbers of the oldlist" ] }, { "cell_type": "code", "execution_count": 57, "id": "e158089b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[25, 9, 36, 4]" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "oldlist = [5, 3, 6, 2]\n", "newlist = []\n", "\n", "for i in oldlist:\n", " newlist.append(i*i)\n", "\n", "newlist" ] }, { "cell_type": "markdown", "id": "28b4708e", "metadata": {}, "source": [ "**You can perform above task in single line using List Comprehension**\n", "\n", "```newlist = [expression for item in iterable]```\n", "\n", "Where,\n", "- `expression` is the member itself, a call to a method, or any other valid expression that returns a value. \n", "- `item` is the object or value in the list or iterable.\n", "- `iterable` is a list, set, sequence, generator, or any other object that can return its elements one at a time.\n" ] }, { "cell_type": "code", "execution_count": 58, "id": "f24e5a17", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[25, 9, 36, 4]" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "oldlist = [5, 3, 6, 2]\n", "\n", "newlist = [i*i for i in oldlist]\n", "\n", "newlist" ] }, { "cell_type": "markdown", "id": "f9c4e549", "metadata": {}, "source": [ "**Example 2:** Given a list, create a new list that should contain the even numbers in the given list using List Comprehension\n", "\n", "```newlist = [expression for item in iterable if (condition == True)]```\n", "\n", "A list comprehension in Python can have four elements:\n", "- `expression` is the member itself, a call to a method, or any other valid expression that returns a value. \n", "- `item` is the object or value in the list or iterable.\n", "- `iterable` is a list, set, sequence, generator, or any other object that can return its elements one at a time.\n", "- `if (condition==True)` The item will be placed in the newlist only if the condition evaluates to True" ] }, { "cell_type": "code", "execution_count": 59, "id": "9db4663f", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[12, 88, 20, 32]" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list1 = [1, 9, 12, 88, 65, 7, 20, 55, 47, 32]\n", "newlist = []\n", "\n", "for i in list1:\n", " if (i%2 == 0):\n", " newlist.append(i)\n", "newlist\n" ] }, { "cell_type": "code", "execution_count": 60, "id": "35ab73b3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[12, 88, 20, 32]" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list1 = [1, 9, 12, 88, 65, 7, 20, 55, 47, 32]\n", "\n", "newlist = [i for i in list1 if (i % 2 == 0)]\n", "\n", "newlist" ] }, { "cell_type": "markdown", "id": "930f03a8", "metadata": {}, "source": [ "**Example 3:** Suppose we want to create a `newlist` from an existing list of `fruits` such that the new list should contain only those fruits having alphabet **`a`** in their name\n", "```newlist = [expression for item in iterable if (condition == True)]```\n", "\n", "A list comprehension in Python can have four elements:\n", "- `expression` is the member itself, a call to a method, or any other valid expression that returns a value. \n", "- `item` is the object or value in the list or iterable.\n", "- `iterable` is a list, set, sequence, generator, or any other object that can return its elements one at a time.\n", "- `if (condition)` The item will be placed in the newlist only if the condition evaluates to true" ] }, { "cell_type": "code", "execution_count": 61, "id": "9fbb53b1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['apple', 'banana', 'mango']\n" ] } ], "source": [ "fruits = [\"apple\", \"banana\", \"cherry\", \"kiwi\", \"mango\"]\n", "newlist = []\n", "\n", "for fruit in fruits:\n", " if \"a\" in fruit:\n", " newlist.append(fruit)\n", "\n", "print(newlist)" ] }, { "cell_type": "code", "execution_count": 62, "id": "c14b3edd", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['apple', 'banana', 'mango']\n" ] } ], "source": [ "fruits = [\"apple\", \"banana\", \"cherry\", \"kiwi\", \"mango\"]\n", "\n", "newlist = [fruit for fruit in fruits if (\"a\" in fruit)]\n", "\n", "print(newlist)" ] }, { "cell_type": "markdown", "id": "f4d58088", "metadata": {}, "source": [ "**Example 4:** Create a `newlist` from an existing list of `fruits` such that the new list should contain all elements less \"kiwi\". Use List Comprehension" ] }, { "cell_type": "code", "execution_count": 63, "id": "42eb28f5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['apple', 'banana', 'cherry', 'mango']\n" ] } ], "source": [ "fruits = [\"apple\", \"banana\", \"cherry\", \"kiwi\", \"mango\"]\n", "\n", "newlist = [fruit for fruit in fruits if (fruit != \"kiwi\")]\n", "\n", "print(newlist)" ] }, { "cell_type": "markdown", "id": "7072faa2", "metadata": {}, "source": [ "## 4. Dictionary Comprehension\n", "- Dictionary comprehension is a concise way to create a new dictionary based on the values of an existing list or dictionary.\n", "\n", "- Let us understand Dictionary comprehension step by step with examples:\n", "```\n", "newdict = {key:value for var in iterable if (condition == True)}\n", "```\n", "- Note for list comprehension we use `[ ]`, while for dictionary comprehension we use `{ }` " ] }, { "cell_type": "markdown", "id": "fa6e53dd", "metadata": {}, "source": [ "**Example 1:** Suppose we have a list containing some random numbers. We want to create a dictionary having keys of that list and values as cubes of the list values" ] }, { "cell_type": "code", "execution_count": 64, "id": "1a06df1c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}\n" ] } ], "source": [ "list1 = [1, 2, 3, 4, 5]\n", "\n", "dict1 = {key: key**3 for key in list1}\n", "\n", "print (dict1)" ] }, { "cell_type": "markdown", "id": "38b8ea13", "metadata": {}, "source": [ "**Example 2:** Suppose we have a list containing numbers from 1 to 10. We want to create a dictionary having dictionary keys as the values of that list and dictionary values as cubes of the values in the list. However, the dictionary should contain only those key:value pairs, where the dictionary values are divisible by 4" ] }, { "cell_type": "code", "execution_count": 65, "id": "a63c44e2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{0: 0, 2: 8, 4: 64, 6: 216, 8: 512, 10: 1000}\n" ] } ], "source": [ "list1 = range(11)\n", "\n", "dict1 = {key: key**3 for key in list1 if key**3 % 4 == 0}\n", "\n", "print(dict1)" ] }, { "cell_type": "markdown", "id": "4268aaf9", "metadata": {}, "source": [ "**Example 3:** Suppose we have a dictionary containing some grossary items and their prices. \n", "```\n", "dict1 = {'milk': 120.0, 'choclate': 45.0, 'bread': 80.0}\n", "```\n", "Use dictionary comprehension to create a new dictionary with increased prices by 25%" ] }, { "cell_type": "code", "execution_count": 66, "id": "5d91b2b5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'milk': 150.0, 'choclate': 56.25, 'bread': 100.0}\n" ] } ], "source": [ "\n", "dict1 = {'milk': 120.0, 'choclate': 45.0, 'bread': 80.0}\n", "increase = 1.25\n", "\n", "dict2 = {key: value*increase for (key, value) in dict1.items()}\n", "\n", "print(dict2)" ] }, { "cell_type": "markdown", "id": "74cae131", "metadata": {}, "source": [ "**Example 4:** Suppose we have a dictionary \n", "```\n", "dict1 = {'alpha': 47, 'bravo': 84, 'charlie': 79, 'delta': 92}\n", "```\n", "\n", "Use Dictionary comprehension to create a new dictionary containing even values only" ] }, { "cell_type": "code", "execution_count": 1, "id": "a3f51a3b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'bravo': 84, 'delta': 92}\n" ] } ], "source": [ "\n", "dict1 = {'alpha': 47, 'bravo': 84, 'charlie': 79, 'delta': 92}\n", "\n", "dict2 = {key: value for (key, value) in dict1.items() if value % 2 == 0}\n", "print(dict2)" ] }, { "cell_type": "code", "execution_count": null, "id": "65a2430f", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "bcdb0f45", "metadata": {}, "source": [ "## Check your Concepts\n", "\n", "Try answering the following questions to test your understanding of the topics covered in this notebook:\n", "\n", "1. What is iteration or looping in programming languages? Why is it useful?\n", "2. What are the two ways for performing iteration in Python?\n", "3. What is the purpose of the `while` statement in Python?\n", "4. What is the syntax of the `white` statement in Python? Give an example.\n", "5. Write a program to compute the sum of the numbers 1 to 100 using a while loop. \n", "6. Repeat the above program for numbers up to 1000, 10000, and 100000. How long does it take each loop to complete?\n", "7. What is an infinite loop?\n", "8. What causes a program to enter an infinite loop?\n", "9. How do you interrupt an infinite loop within Jupyter?\n", "10. What is the purpose of the `break` statement in Python? \n", "11. Give an example of using a `break` statement within a while loop.\n", "12. What is the purpose of the `continue` statement in Python?\n", "13. Give an example of using the `continue` statement within a while loop.\n", "14. What is logging? How is it useful?\n", "15. What is the purpose of the `for` statement in Python?\n", "16. What is the syntax of `for` loops? Give an example.\n", "17. How are for loops and while loops different?\n", "18. How do you loop over a string? Give an example.\n", "19. How do you loop over a list? Give an example.\n", "20. How do you loop over a tuple? Give an example.\n", "21. How do you loop over a dictionary? Give an example.\n", "22. What is the purpose of the `range` statement? Give an example.\n", "23. What is the purpose of the `enumerate` statement? Give an example.\n", "24. How are the `break`, `continue`, and `pass` statements used in for loops? Give examples.\n", "25. Can loops be nested within other loops? How is nesting useful?\n", "26. Give an example of a for loop nested within another for loop.\n", "27. Give an example of a while loop nested within another while loop.\n", "28. Give an example of a for loop nested within a while loop.\n", "29. Give an example of a while loop nested within a for loop.\n", "30. Give a detailed comparison between map() and list comprehension, which is better in which scenario. Use timeit to time different codes\n" ] }, { "cell_type": "code", "execution_count": null, "id": "6be7fb2a", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "d7670e6d", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "af6706e2", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7" } }, "nbformat": 4, "nbformat_minor": 5 }