{ "cells": [ { "cell_type": "markdown", "id": "0ba08993", "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": "007946c5", "metadata": {}, "source": [ "

Lecture 2.12

" ] }, { "cell_type": "markdown", "id": "47555ad0", "metadata": {}, "source": [ "\"Open" ] }, { "cell_type": "markdown", "id": "ae18f83a", "metadata": {}, "source": [ "## _Advance-Functions.ipynb_" ] }, { "cell_type": "markdown", "id": "f7fefd5f", "metadata": {}, "source": [ "## Review of Python Functions\n", " " ] }, { "cell_type": "markdown", "id": "4377d061", "metadata": {}, "source": [ "## Learning agenda of this notebook\n", "1. Anonymous / Lambda Functions\n", "2. Using lambda function as argument to other functions\n", "3. Using Lambda Function with built-in `map()` function\n", "4. Using Lambda Function with built-in `filter()` function\n", "5. Using Lambda Function with built-in `reduce()` function\n", "6. Using Lambda Function with built-in `sorted()` function\n", "7. Bonus\n", " - The `zip()` function\n", " - Iterators and Generators" ] }, { "cell_type": "markdown", "id": "c32289dd", "metadata": {}, "source": [ "## 1. Lambda / Anonymous Functions\n", "The syntax of defining a lambda function is:**```lambda [arg1 [,arg2,.....argn]]:expression```**\n", "\n", " " ] }, { "cell_type": "markdown", "id": "a59dbb94", "metadata": {}, "source": [ "### a. Example 1: A function that is passed one argument and it returns its square\n", "- Let us do this example step by step to completely understand the process of writing lambda functions" ] }, { "cell_type": "code", "execution_count": 1, "id": "34ef71d0", "metadata": {}, "outputs": [], "source": [ "def square1(num):\n", " result = num**2\n", " return result" ] }, { "cell_type": "code", "execution_count": 2, "id": "3f58a3a9", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "25" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rv = square1(5)\n", "rv" ] }, { "cell_type": "markdown", "id": "1e043224", "metadata": {}, "source": [ "**Let us try to shrink the above function**" ] }, { "cell_type": "code", "execution_count": 3, "id": "3adb1820", "metadata": {}, "outputs": [], "source": [ "def square2(num):\n", " return num**2" ] }, { "cell_type": "code", "execution_count": 4, "id": "5d5e8e04", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "25" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rv = square2(5)\n", "rv" ] }, { "cell_type": "markdown", "id": "c0fbdee9", "metadata": {}, "source": [ "**Although not a good programming style, however, we can write this in a single line**" ] }, { "cell_type": "code", "execution_count": 5, "id": "11b36c1c", "metadata": {}, "outputs": [], "source": [ "def square3(num): return num**2" ] }, { "cell_type": "code", "execution_count": 6, "id": "0efd7475", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "25" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rv = square3(5)\n", "rv" ] }, { "cell_type": "markdown", "id": "7c920c1f", "metadata": {}, "source": [ "**This is the form a function that a lambda expression intends to replicate. A lambda expression can then be written as:**" ] }, { "cell_type": "code", "execution_count": 7, "id": "3849336b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(num)>" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lambda num: num**2" ] }, { "cell_type": "markdown", "id": "379106bb", "metadata": {}, "source": [ "Note how we get a function back. We can assign this function to a label:" ] }, { "cell_type": "code", "execution_count": 1, "id": "c65a5e05", "metadata": {}, "outputs": [], "source": [ "square4 = lambda num: num**2" ] }, { "cell_type": "code", "execution_count": 2, "id": "4f679782", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " at 0x7f8f138bda60>\n", "\n" ] } ], "source": [ "print(square4) \n", "print(type(square4))" ] }, { "cell_type": "code", "execution_count": 3, "id": "2a09cf7e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "25" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rv = square4(5)\n", "rv" ] }, { "cell_type": "markdown", "id": "39967b54", "metadata": {}, "source": [ "### b. Example 2: A function that is passed two arguments and it returns their sum\n", "```\n", "def mysum2(a, b):\n", " return a+b\n", "\n", "rv = mysum2(5, 7)\n", "rv\n", "```" ] }, { "cell_type": "code", "execution_count": 11, "id": "dbd801c5", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "12.3" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mysum2 = lambda a, b: a + b \n", "\n", "rv = mysum2(5.3, 7)\n", "rv\n" ] }, { "cell_type": "markdown", "id": "a58afa45", "metadata": {}, "source": [ "### c. Example 3: A function that is passed three arguments and it returns their sum\n", "```\n", "def mysum3(a, b, c):\n", " return a+b+c\n", "\n", "rv = mysum3(5, 7, 9)\n", "rv\n", "```" ] }, { "cell_type": "code", "execution_count": 12, "id": "ecf73362", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "14.5" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mysum3 = lambda a, b, c: a + b + c \n", "\n", "rv = mysum3(5.5, 6.3, 2.7) # return type corresponds to the expression\n", "rv" ] }, { "cell_type": "markdown", "id": "d2f8a7b8", "metadata": {}, "source": [ "### d. Example 4: A function that is passed one argument and it returns True if it is even and False otherwise" ] }, { "cell_type": "code", "execution_count": 13, "id": "e3a29b0e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "even = lambda x: x % 2 == 0\n", "rv = even(3) # return type corresponds to the expression\n", "rv" ] }, { "cell_type": "markdown", "id": "6587c070", "metadata": {}, "source": [ "### e. Example 5: A function that is passed a string and returns the first character of that string" ] }, { "cell_type": "code", "execution_count": 14, "id": "251187ee", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'H'" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "func = lambda s: s[0]\n", "rv = func(\"Hello\")\n", "rv" ] }, { "cell_type": "markdown", "id": "e51141e7", "metadata": {}, "source": [ "### f. Example 6: A function that is passed a string, it returns the reverse of that string" ] }, { "cell_type": "code", "execution_count": 15, "id": "fd5a4bc7", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'olleH'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "func = lambda s: s[::-1]\n", "\n", "rv = func(\"Hello\")\n", "rv" ] }, { "cell_type": "markdown", "id": "7c71a973", "metadata": {}, "source": [ "### g. Example 7: A function that is passed a list and it returns the length of the list" ] }, { "cell_type": "code", "execution_count": 16, "id": "0a5731c6", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "func = lambda arg: len(arg)\n", "\n", "list1 = ['Learning', 'is', 'fun', 'with', 'arif']\n", "rv = func(list1)\n", "rv" ] }, { "cell_type": "markdown", "id": "12493fbe", "metadata": {}, "source": [ ">**The real usage of Python Lambda functions is actually passing them as arguments to other functions like `map()`,`filter()` and `reduce()`**" ] }, { "cell_type": "markdown", "id": "3101c48e", "metadata": {}, "source": [ "## 2. Using Lambda Function as Argument to other Functions" ] }, { "cell_type": "markdown", "id": "94d5169a", "metadata": {}, "source": [ "**Three regular function definitions and their calling convention**" ] }, { "cell_type": "code", "execution_count": 17, "id": "03cb8588", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(10, 6, 16)" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Some basic functions that receives two arguments and return their sum, diff, mul\n", "def myadd(a, b):\n", " return a + b\n", "\n", "def mysub(a, b):\n", " return a - b\n", "\n", "def mymul(a, b):\n", " return a * b\n", "\n", "# Calling above functions\n", "rv1 = myadd(8,2)\n", "rv2 = mysub(8, 2)\n", "rv3 = mymul(8, 2)\n", "rv1, rv2, rv3" ] }, { "cell_type": "markdown", "id": "e92f4c66", "metadata": {}, "source": [ "**We can write above three functions as lambda functions**" ] }, { "cell_type": "code", "execution_count": 18, "id": "c378ae15", "metadata": {}, "outputs": [], "source": [ "myadd = lambda a, b: a+b\n", "mysub = lambda a, b: a-b\n", "mymul = lambda a, b: a*b" ] }, { "cell_type": "markdown", "id": "65069f6b", "metadata": {}, "source": [ "**Now, let us write a calculator function that other than receiving two arguments, also receives a function name which specifies the operation that needs to be performed on the arguments**" ] }, { "cell_type": "code", "execution_count": 19, "id": "ee10f6be", "metadata": {}, "outputs": [], "source": [ "def mycalc(op, a, b):\n", " return op(a,b)" ] }, { "cell_type": "code", "execution_count": 20, "id": "204fb457", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(10, 6, 16)" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rv1 = mycalc(myadd, 8, 2)\n", "rv2 = mycalc(mysub, 8, 2)\n", "rv3 = mycalc(mymul, 8, 2)\n", "\n", "rv1, rv2, rv3" ] }, { "cell_type": "markdown", "id": "fdc1fb07", "metadata": {}, "source": [ "**A more elegant way of writing above code**" ] }, { "cell_type": "code", "execution_count": 21, "id": "69a5a0b5", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(10, 6, 6)" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rv1 = mycalc(lambda a, b: a + b, 8, 2)\n", "rv2 = mycalc(lambda a, b: a - b, 8, 2)\n", "rv3 = mycalc(lambda a, b: a - b, 8, 2)\n", "\n", "rv1, rv2, rv3" ] }, { "cell_type": "markdown", "id": "c0d00af9", "metadata": {}, "source": [ "## 3. Using Lambda Function as Argument to built-in `map()` Function\n", "- The ```map(aFunction, *iterables)``` function simply returns a map object after applying `aFunction()` to all the elements of `iterable(s)`. Later you can type cast the map object to appropriate data structure\n", "- The original iterable(s) remains unchanged. " ] }, { "cell_type": "code", "execution_count": 22, "id": "8a4a3e62", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class map in module builtins:\n", "\n", "class map(object)\n", " | map(func, *iterables) --> map object\n", " | \n", " | Make an iterator that computes the function using arguments from\n", " | each of the iterables. Stops when the shortest iterable is exhausted.\n", " | \n", " | Methods defined here:\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | __iter__(self, /)\n", " | Implement iter(self).\n", " | \n", " | __next__(self, /)\n", " | Implement next(self).\n", " | \n", " | __reduce__(...)\n", " | Return state information for pickling.\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" ] } ], "source": [ "help(map)" ] }, { "cell_type": "markdown", "id": "042c3b5f", "metadata": {}, "source": [ "### a. Example 1: \n", "**Given a list of numbers, suppose we want to create a new list in which every element is the square every item of the given list**" ] }, { "cell_type": "markdown", "id": "dcbd3652", "metadata": {}, "source": [ "**Option 1: We can do this using a simple loop**" ] }, { "cell_type": "code", "execution_count": 23, "id": "6f1f0056", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original list: [5, 7, 2, 6, 9]\n", "List with items squared: [25, 49, 4, 36, 81]\n" ] } ], "source": [ "mylist = [5, 7, 2, 6, 9]\n", "\n", "mylist_squared = [] # create an empty list\n", "for a in mylist:\n", " mylist_squared.append(a**2) # append new item at the end of the newly created list\n", "\n", "print(\"Original list: \", mylist)\n", "print(\"List with items squared: \", mylist_squared)" ] }, { "cell_type": "markdown", "id": "7b287fc5", "metadata": {}, "source": [ "**Option 2: We can do this using `map()` function and passing an appropriate regular function as its first argument**" ] }, { "cell_type": "code", "execution_count": 24, "id": "7800b53e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original list: [5, 7, 2, 6, 9]\n", "List with items squared: [25, 49, 4, 36, 81]\n" ] } ], "source": [ "mylist = [5, 7, 2, 6, 9]\n", "\n", "def sqr(x):\n", " return x ** 2\n", "\n", "\n", "map_object = map(sqr, mylist)\n", "\n", "mylist_squared = list(map_object)\n", "\n", "print(\"Original list: \", mylist)\n", "print(\"List with items squared: \", mylist_squared)" ] }, { "cell_type": "markdown", "id": "244cd0e5", "metadata": {}, "source": [ "- We passed a user defined function `sqr(x)`, to the `map` function, along with the list of items on which to apply that function\n", "- `map()` function calls `sqr()` function on each list item and collects all the return values into a map object, which is type casted to a list\n", "- Since `map()` expects a function to be passed in, so this is where we can also use lambda functions as shown below" ] }, { "cell_type": "markdown", "id": "cc317bfb", "metadata": {}, "source": [ "**Let us use Lambda Function as key argument to `map()` function to perform the above task**" ] }, { "cell_type": "code", "execution_count": 25, "id": "b8ba4b99", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original list: [5, 7, 2, 6, 9]\n", "List with items squared: [25, 49, 4, 36, 81]\n" ] } ], "source": [ "mylist = [5, 7, 2, 6, 9]\n", "\n", "map_object = map(lambda x: x ** 2 , mylist)\n", "\n", "mylist_squared = list(map_object)\n", "\n", "print(\"Original list: \", mylist)\n", "print(\"List with items squared: \", mylist_squared)" ] }, { "cell_type": "markdown", "id": "a7f51bce", "metadata": {}, "source": [ "**Let us do this with List comprehension**" ] }, { "cell_type": "code", "execution_count": 26, "id": "729dabcd", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[25, 49, 4, 36, 81]" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist = [5, 7, 2, 6, 9]\n", "newlist = [i**2 for i in mylist]\n", "newlist" ] }, { "cell_type": "markdown", "id": "2fb35e15", "metadata": {}, "source": [ "### b. Example 2: \n", "**Given a list of numbers, suppose we want to create a new list in which every element is the remainder once the original list element is divided by 5**" ] }, { "cell_type": "code", "execution_count": 27, "id": "ab937bbb", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original list: [74, 85, 14, 23, 56, 32, 45]\n", "List of remainders: [4, 0, 4, 3, 1, 2, 0]\n" ] } ], "source": [ "mylist = [74, 85, 14, 23, 56, 32, 45 ]\n", "\n", "map_object = map(lambda num: num%5, mylist)\n", "\n", "remainders = list(map_object)\n", "\n", "print(\"Original list: \", mylist)\n", "print(\"List of remainders: \", remainders)" ] }, { "cell_type": "code", "execution_count": null, "id": "e47b575e", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "47928f90", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "08860906", "metadata": {}, "source": [ "### c. Example 3: \n", "**Suppose we want to add two lists**" ] }, { "cell_type": "code", "execution_count": 28, "id": "a330e6b4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sum of the two lists: [7, 9, 5, 8]\n" ] } ], "source": [ "mylist1 = [4, 8, 3, 2]\n", "mylist2 = [3, 1, 2, 6]\n", "\n", "result = map(lambda a, b: a + b, mylist1, mylist2) #two arguments are passed to lambda func (one from each list)\n", "result = list(result)\n", "\n", "print(\"Sum of the two lists: \", result)" ] }, { "cell_type": "markdown", "id": "8317cefe", "metadata": {}, "source": [ "### d. Example 4: \n", "**Given a list of strings, suppose we want to create another list that contains the length of each string in the list**" ] }, { "cell_type": "code", "execution_count": 29, "id": "ff9ded98", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Length of Strings in list1: [7, 9, 9, 4]\n" ] } ], "source": [ "list1 = ('Mujahid', 'Arif Butt', 'Kakamanna', 'Maaz')\n", "\n", "result = map(lambda a: len(a), list1)\n", "result = list(result)\n", "\n", "print(\"Length of Strings in list1: \", result)" ] }, { "cell_type": "markdown", "id": "4bb135cb", "metadata": {}, "source": [ "## 4. Using Lambda Function as Argument to built-in `filter()` Function\n", "```\n", "filter(function or None, iterable)\n", "```\n", "- The `filter()` function offers a convenient way to filter out all the elements of an iterable, for which the function returns true.\n", "- If function argument is None, return the items that are itself True.\n", "- The filter object contains only those items of iterable for which `function(item)` returns True. \n", "- The original iterable remains unchanged. \n", "- The filter object can be converted to a list using the `list()` function" ] }, { "cell_type": "markdown", "id": "bbbfc7f8", "metadata": {}, "source": [ "### a. Example 1: \n", "**A very basic usage of `filter()`, that returns the True elements of a list**\n", "- In Python, the following objects are considered false:\n", " >- Constants like `None` and `False`\n", " >- Numeric types having values: 0, 0.0, 0j\n", " >- Empty sequences and collections like `\"\"`, `()`, `[]`, `{}`, `set()`, and `range(0)`" ] }, { "cell_type": "code", "execution_count": 30, "id": "1d307c7e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "[5, -3, True, 9, 8]\n" ] } ], "source": [ "mylist = [5, 0, -3, {}, False, 0.0, True, 9, 0j, (), None, 8]\n", "\n", "result = filter(None, mylist)\n", "print(result)\n", "print(list(result))" ] }, { "cell_type": "markdown", "id": "fb82490b", "metadata": {}, "source": [ "### b. Example 2: \n", "**Suppose we want to extract even numbers from a list**" ] }, { "cell_type": "code", "execution_count": 31, "id": "c94c7b27", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Even numbers in the list are: [4, 6, 8, 12]\n" ] } ], "source": [ "numbers = [1, 5, 4, 6, 8, 11, 3, 12]\n", "\n", "result = filter(lambda x: x%2 == 0 , numbers)\n", "\n", "result = list(result)\n", "\n", "print(\"Even numbers in the list are: \", result)" ] }, { "cell_type": "markdown", "id": "3227e2ef", "metadata": {}, "source": [ "**Let us do it using List Comprehension**" ] }, { "cell_type": "code", "execution_count": 32, "id": "24ff0082", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[4, 6, 8, 12]" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "numbers = [1, 5, 4, 6, 8, 11, 3, 12]\n", "newlist = [i for i in numbers if i%2 == 0]\n", "newlist" ] }, { "cell_type": "markdown", "id": "eb8125ee", "metadata": {}, "source": [ "### c. Example 3: \n", "**Suppose we want to extract negative numbers from a list**" ] }, { "cell_type": "code", "execution_count": 33, "id": "a63237fb", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Negative numbers in the list are: [-3, -8, -3, -7]\n" ] } ], "source": [ "numbers = [25, -3, -8, 17, 3, 8, -3, 6, -7, 0]\n", "\n", "result = filter(lambda x: x<0, numbers)\n", "\n", "result = list(result)\n", "\n", "print(\"Negative numbers in the list are: \", result)" ] }, { "cell_type": "markdown", "id": "af17ee88", "metadata": {}, "source": [ "### d. Example 4: \n", "**Suppose we want to extract vowels from a list of alphabets**" ] }, { "cell_type": "code", "execution_count": 34, "id": "2e48544d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Vowels in the list are: ['i', 'a', 'e']\n" ] } ], "source": [ "characters = ['i', 'z', 'b', 'a', 'd', 'f', 't', 'e','w', 'x']\n", "\n", "vowels = ['a', 'e', 'i', 'o', 'u']\n", " \n", "result = filter(lambda x: x in vowels, characters)\n", "\n", "result = list(result) \n", "print(\"Vowels in the list are: \", result)" ] }, { "cell_type": "markdown", "id": "581ebe37", "metadata": {}, "source": [ "## 5. Using Lambda Function as Argument to built-in `reduce()` Function\n", "- The `reduce()` works differently than `map()` and `filter()`. It does not return a new iterable based on the function and iterable we've passed. Instead, it returns a single value.\n", "```\n", "reduce(func, sequence[, initial])\n", "```\n", " \n", "\n", "- If seq = `[ s1, s2, s3, ... , sn ]`, then calling `reduce(func, seq)` works like this:\n", " - Apply `func` argument to the first two items in the iterable and generate a partial result, i.e. `func(s1,s2)`\n", " - The list on which `reduce()` works looks now like this: `[ func(s1, s2), s3, ... , sn ]`\n", " - In the next step the function will be applied on the previous result and the third element of the list, i.e. `func(func(s1, s2),s3)`\n", " - The list looks like this now: `[ function(function(s1, s2),s3), ... , sn ]`\n", " - It continues like this until just one element is left and return this element as the result of `reduce()`\n", "- If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. The optional argument `initial` when provided is used as the 0th element\n", "- In Python 3.x, if you need to use `reduce()`, then you first have to import the function into your current scope using an import statement in one of the following ways:\n", " - `import functools` and then use fully-qualified names like functools.reduce().\n", " - `from functools import reduce` and then call reduce() directly.\n", " " ] }, { "cell_type": "markdown", "id": "849211fc", "metadata": {}, "source": [ "### a. Example 1: \n", "**Suppose given a list of numbers and we want to get the accumulative sum of all the numbers in that list**" ] }, { "cell_type": "markdown", "id": "579f0d01", "metadata": {}, "source": [ "**Option 1: We can do this using a simple loop**" ] }, { "cell_type": "code", "execution_count": 35, "id": "0dfd11ac", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "113" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "numbers = [47, 11, 42, 13]\n", "total = 0\n", "\n", "for i in numbers:\n", " total += i\n", "\n", "total" ] }, { "cell_type": "markdown", "id": "4b99df2c", "metadata": {}, "source": [ "**Option 2: We can do this using `reduce()` function and passing an appropriate regular function as its first argument. Remember this has to be a function that receives two arguments**" ] }, { "cell_type": "code", "execution_count": 36, "id": "af79a735", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "113" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Example: Note the call to reduce(), \n", "# applies myadd() to the items in the numbers list to compute their accumulative sum \n", "\n", "from functools import reduce\n", "def myadd(a,b):\n", " return a+b\n", "\n", "numbers = [47, 11, 42, 13]\n", "\n", "rv = reduce(myadd, numbers)\n", "rv" ] }, { "cell_type": "markdown", "id": "3e8193fc", "metadata": {}, "source": [ "**Option 3: Let us use Lambda Function as first argument to `reduce()` function to perform the above task**" ] }, { "cell_type": "code", "execution_count": 37, "id": "6b8d8fd0", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "113" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Example: Use lambda function for above task\n", "from functools import reduce\n", "numbers = [47, 11, 42, 13]\n", "\n", "rv = reduce(lambda x,y: x+y, numbers)\n", "rv" ] }, { "cell_type": "markdown", "id": "bdc78532", "metadata": {}, "source": [ "**Let us now understand the initial argument to `reduce()` function**\n", "```\n", "reduce(func, sequence[, initial])\n", "```" ] }, { "cell_type": "code", "execution_count": 38, "id": "0ff62f2e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "123" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Example: Use of initial argument of reduce() function\n", "from functools import reduce\n", "numbers = [47, 11, 42, 13]\n", "\n", "rv = reduce(lambda x,y:x+y, numbers, 10)\n", "rv" ] }, { "cell_type": "markdown", "id": "00a7f66d", "metadata": {}, "source": [ "### b. Example 2: \n", "**Multiplying all numeric values of a list with each other**" ] }, { "cell_type": "code", "execution_count": 39, "id": "d3ec6fa4", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "120" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from functools import reduce\n", "numbers = [1, 2, 3, 4, 5]\n", "\n", "rv = reduce(lambda x,y: x*y, numbers)\n", "rv" ] }, { "cell_type": "markdown", "id": "4716bb03", "metadata": {}, "source": [ "### c. Example 3: \n", "**Finding minimum or maximum number from a list of numbers**" ] }, { "cell_type": "code", "execution_count": 12, "id": "0bcb4894", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "numbers = [-10, -20, -93, -4, -5]\n", "\n", "\n", "rv1 = reduce(lambda a, b: a if a > b else b, numbers, 0)\n", "\n", "\n", "rv1" ] }, { "cell_type": "code", "execution_count": 40, "id": "64e86f49", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(4, 93)" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from functools import reduce\n", "numbers = [10, 20, 93, 4, 5]\n", "\n", "\n", "rv1 = reduce(lambda a, b: a if a < b else b, numbers)\n", "rv2 = reduce(lambda a, b: a if a > b else b, numbers)\n", "\n", "rv1, rv2" ] }, { "cell_type": "markdown", "id": "de66bb0b", "metadata": {}, "source": [ "### d. Example 4: \n", "**Checking if ALL values in an iterable are true**" ] }, { "cell_type": "code", "execution_count": 41, "id": "c9bfeb00", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from functools import reduce\n", "mylist = [0, 0, 1, 0, 0]\n", "\n", "rv = reduce(lambda a, b: bool(a and b), mylist)\n", "rv\n" ] }, { "cell_type": "markdown", "id": "e0e1aa39", "metadata": {}, "source": [ "### e. Example 5: \n", "**Checking if ANY value in an iterable is true**" ] }, { "cell_type": "code", "execution_count": 42, "id": "e6039528", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from functools import reduce\n", "mylist = [0, 0, 1, 0, 0]\n", "\n", "rv = reduce(lambda a, b: bool(a | b), mylist)\n", "rv\n" ] }, { "cell_type": "markdown", "id": "1a71d9db", "metadata": {}, "source": [ "## 6. Using Lambda Function as Argument to built-in `sorted()` Function\n", "- We have already seen the use of `sorted()` function in our previous session of Tuples.\n", "- The only required argument to `sorted()` function is an iterable. \n", "- It sorts the items of the given iterable in ascending order (by default) and returns the sorted iterable as a list, without modifying the original iterable.\n", "```\n", "sorted(iterable, key=None, reverse=False)\n", "```\n", "We also have seen the use of `key` argument, where we can pass a function that is applied once to each element of the iterable before sorting it." ] }, { "cell_type": "markdown", "id": "e98ce7de", "metadata": {}, "source": [ "### a. Example 1: \n", "**Consider a tuple of strings `('abcz', 'xyza', 'bas', 'arif')`. If we pass this tuple to `sorted()` function, it will sort the list alphabatically.**" ] }, { "cell_type": "code", "execution_count": 43, "id": "8ea3d413", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sorted tuple: ['abcz', 'arif', 'bas', 'xyza']\n", "Original tuple remains as such: ('abcz', 'xyza', 'bas', 'arif')\n" ] } ], "source": [ "t1 = ('abcz', 'xyza', 'bas', 'arif')\n", "\n", "rv = sorted(t1)\n", "\n", "print(\"Sorted tuple: \", rv)\n", "print(\"Original tuple remains as such: \", t1)" ] }, { "cell_type": "markdown", "id": "d0eac8eb", "metadata": {}, "source": [ "**Suppose, we want to sort the above tuple by last character of strings within the tuple so that the output is like : `('xyza', 'arif', 'bas', 'abcz')`. We can do this by passing an appropriate regular function to `key` argument of the `sorted()` function**" ] }, { "cell_type": "code", "execution_count": null, "id": "fd98107d", "metadata": {}, "outputs": [], "source": [ "def last(s):\n", " return s[-1]\n", "\n", "t1 = ('abcz', 'xyza', 'bas', 'arif')\n", "rv = sorted(t1, key=last)\n", "\n", "print(\"Sorted tuple: \", rv)\n", "print(\"Original tuple remains as such: \", t1)" ] }, { "cell_type": "markdown", "id": "5d4a9753", "metadata": {}, "source": [ "**Let us use Lambda Function as `key` argument to `sorted()` function to perform the above task**" ] }, { "cell_type": "code", "execution_count": 44, "id": "3a6ec1e4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sorted tuple: ['xyza', 'arif', 'bas', 'abcz']\n", "Original tuple remains as such: ('abcz', 'xyza', 'bas', 'arif')\n" ] } ], "source": [ "t1 = ('abcz', 'xyza', 'bas', 'arif')\n", "\n", "rv = sorted(t1, key = lambda arg : arg[-1])\n", "\n", "print(\"Sorted tuple: \", rv)\n", "print(\"Original tuple remains as such: \", t1)" ] }, { "cell_type": "markdown", "id": "82c08ba2", "metadata": {}, "source": [ "### b. Example 2: \n", "**Suppose given a list in which each element is a two valued tuple `[(4, 30), (6, 15), (1, 25), (9, 8)]`. If we call `sorted()` function on this list it will sort it based on the first element of each tuple.**" ] }, { "cell_type": "markdown", "id": "494c7ec9", "metadata": {}, "source": [ "**Simple sorting of above list using `sorted()` function, will sort by first element**" ] }, { "cell_type": "code", "execution_count": 45, "id": "969640a2", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(1, 25), (4, 30), (6, 15), (9, 8)]" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist = [(4, 30), (6, 15), (1, 25), (9, 8)]\n", "\n", "\n", "mylist_sorted = sorted(mylist)\n", "\n", "mylist_sorted\n" ] }, { "cell_type": "code", "execution_count": null, "id": "3f3dfc5a", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "fa7c0255", "metadata": {}, "source": [ "**But we want to sort the above list based on the second element of each tuple, so that the output is like: `[(9, 8), (6, 15), (1, 25), (4, 30)]`. We can do this by passing an appropriate regular function to `key` argument of the `sorted()` function**" ] }, { "cell_type": "code", "execution_count": 46, "id": "3803626b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(9, 8), (6, 15), (1, 25), (4, 30)]" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist = [(4, 30), (6, 15), (1, 25), (9, 8)]\n", "\n", "def func(item):\n", " return item[1]\n", "\n", "mylist_sorted = sorted(mylist, key = func)\n", "\n", "mylist_sorted" ] }, { "cell_type": "code", "execution_count": null, "id": "fe0b5b01", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "620c5575", "metadata": {}, "source": [ "**Let us use Lambda Function as `key` argument to `sorted()` function to perform the above task**" ] }, { "cell_type": "code", "execution_count": 47, "id": "2a91cd3d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(9, 8), (6, 15), (1, 25), (4, 30)]" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist = [(4, 30), (6, 15), (1, 25), (9, 8)]\n", "\n", "mylist_sorted = sorted(mylist, key = lambda element:element[1])\n", "\n", "mylist_sorted" ] }, { "cell_type": "code", "execution_count": null, "id": "a4250b43", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "ef99e51d", "metadata": {}, "source": [ "## 7. Bonus" ] }, { "cell_type": "markdown", "id": "4f9e2211", "metadata": {}, "source": [ "### a. The `zip()` Function\n", "- The `zip(*iterables)` function returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. \n", "- The iterator stops when the shortest input iterable is exhausted. \n", "- With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator." ] }, { "cell_type": "code", "execution_count": 48, "id": "a9d3bcfb", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(1, 4), (2, 5), (3, 6)]" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = [1,2,3]\n", "y = [4,5,6]\n", "\n", "zip_object = zip(x ,y)\n", "\n", "mylist = list(zip_object)\n", "mylist" ] }, { "cell_type": "code", "execution_count": 49, "id": "714de2d7", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = [1, 2, 3, 4]\n", "y = [5, 6, 7, 8]\n", "z = [9, 10, 11, 12]\n", "\n", "zip_object = zip(x,y,z)\n", "\n", "mylist = list(zip_object)\n", "mylist" ] }, { "cell_type": "markdown", "id": "4de59c7f", "metadata": {}, "source": [ "**The iterator stops when the shortest input iterable is exhausted.**" ] }, { "cell_type": "code", "execution_count": 50, "id": "db4cbda3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(1, 4), (2, 5), (3, 6)]" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = [1,2,3]\n", "y = [4,5,6,7,8]\n", "\n", "zip_object = zip(x,y)\n", "\n", "mylist = list(zip_object)\n", "mylist" ] }, { "cell_type": "markdown", "id": "0d864536", "metadata": {}, "source": [ "**With a single iterable argument, it returns an iterator of 1-tuples.**" ] }, { "cell_type": "code", "execution_count": 51, "id": "a7ba2d62", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(1,), (2,), (3,), (4,)]" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = [1, 2, 3, 4]\n", "\n", "zip_object = zip(x)\n", "\n", "mylist = list(zip_object)\n", "mylist" ] }, { "cell_type": "markdown", "id": "3c96cc44", "metadata": {}, "source": [ "**With no arguments, it returns an empty iterator.**" ] }, { "cell_type": "code", "execution_count": 52, "id": "048d8dfb", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "zip_object = zip()\n", "\n", "mylist = list(zip_object)\n", "mylist" ] }, { "cell_type": "code", "execution_count": null, "id": "98a85eba", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "1b84cba2", "metadata": {}, "source": [ "### b. Iterators and Generators\n", "**Iterators:**\n", "- In our previous session of `for` loops, we discussed the concept of `Iterator` object, which is used to iterate over iterable objects like lists and tuples.\n", "- We also discussed the `iter()` function, which is passed an iterable (list, tuple, ...) and it returns an iterator for that iterable object. \n", "- We also discussed the `next()` function, which is passed the iterator object, and each time it is called it returns the next item of that iterator object." ] }, { "cell_type": "markdown", "id": "a54a3f48", "metadata": {}, "source": [ "**Example: Iterator Objects**" ] }, { "cell_type": "code", "execution_count": 53, "id": "f8277e30", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist = ['banana', 'mango', 'grapes']\n", "a = iter(mylist)\n", "a" ] }, { "cell_type": "code", "execution_count": 54, "id": "423654a3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "banana\n", "mango\n", "grapes\n" ] } ], "source": [ "print(next(a))\n", "print(next(a))\n", "print(next(a))" ] }, { "cell_type": "code", "execution_count": 55, "id": "dd016ecd", "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_28226/1242322984.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\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": [ "next(a)" ] }, { "cell_type": "code", "execution_count": null, "id": "471059e8", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "0656e2c2", "metadata": {}, "source": [ "**Generators:**\n", "- Today let me tell you as how to write a generator function in Python. A generator is a function that can send back a value and then later resume its execution from where it left off. \n", "- A generator function allows us to generate a sequence of values over time. \n", "- The main difference between a regular function and a generator function is that instead of using a `return` statement, the generator function uses the `yield` statement\n", "- So once a generator function is called, it don't actually return a value and then exit, rather it automatically suspend and resume its execution and state around the last point of value generation. " ] }, { "cell_type": "markdown", "id": "f1ac006f", "metadata": {}, "source": [ "**Example 1: Writing a Hello World Generator Function to understand the `yield` keyword**" ] }, { "cell_type": "code", "execution_count": 56, "id": "2bdd044f", "metadata": {}, "outputs": [], "source": [ "def mygenerator():\n", " print('First item')\n", " yield 10\n", "\n", " print('Second item')\n", " yield 20\n", "\n", " print('Last item')\n", " yield 30" ] }, { "cell_type": "code", "execution_count": 57, "id": "e46292a1", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "gen = mygenerator() \n", "gen" ] }, { "cell_type": "code", "execution_count": 58, "id": "8aad8d9c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First item\n", "10\n" ] } ], "source": [ "print(next(gen))" ] }, { "cell_type": "code", "execution_count": 59, "id": "4a3e4371", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Second item\n", "20\n" ] } ], "source": [ "print(next(gen))" ] }, { "cell_type": "code", "execution_count": 60, "id": "f1e579ad", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Last item\n", "30\n" ] } ], "source": [ "print(next(gen))" ] }, { "cell_type": "code", "execution_count": null, "id": "ae155707", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "be124289", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "a53d9489", "metadata": {}, "source": [ "**Example 2: Writing a Generator Function that returns cubes of numbers**" ] }, { "cell_type": "code", "execution_count": 61, "id": "8a427867", "metadata": {}, "outputs": [], "source": [ "def gencubes(n):\n", " for num in range(n):\n", " yield num**3" ] }, { "cell_type": "code", "execution_count": 62, "id": "550e73ec", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "8\n", "27\n", "64\n" ] } ], "source": [ "for x in gencubes(5):\n", " print(x)" ] }, { "cell_type": "markdown", "id": "cc347d82", "metadata": {}, "source": [ ">**The main advantage of using a generator function over the iterator is that elements are generated dynamically. Since the next item is generated only after the first is consumed, it is more memory efficient than the iterator.**" ] }, { "cell_type": "code", "execution_count": null, "id": "29353480", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "d9de52f9", "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 a function?\n", "2. What are the benefits of using functions?\n", "3. What are some built-in functions in Python?\n", "4. How do you define a function in Python? Give an example.\n", "5. What is the body of a function?\n", "6. When are the statements in the body of a function executed?\n", "7. What is meant by calling or invoking a function? Give an example.\n", "8. What are function arguments? How are they useful?\n", "9. How do you store the result of a function in a variable?\n", "10. What is the purpose of the `return` keyword in Python?\n", "11. Can you return multiple values from a function?\n", "12. Can a `return` statement be used inside an `if` block or a `for` loop?\n", "13. Can the `return` keyword be used outside a function?\n", "14. What is scope in a programming region? \n", "15. How do you define a variable inside a function?\n", "16. What are local & global variables?\n", "17. Can you access the variables defined inside a function outside its body? Why or why not?\n", "18. What do you mean by the statement \"a function defines a scope within Python\"?\n", "19. Do for and while loops define a scope, like functions?\n", "20. Do if-else blocks define a scope, like functions?\n", "21. What are optional function arguments & default values? Give an example.\n", "22. Why should the required arguments appear before the optional arguments in a function definition?\n", "23. How do you invoke a function with named arguments? Illustrate with an example.\n", "24. Can you split a function invocation into multiple lines?\n", "25. Write a function that takes a number and rounds it up to the nearest integer.\n", "26. What is a docstring? Why is it useful?\n", "27. How do you display the docstring for a function?\n", "28. What are *args and **kwargs? How are they useful? Give an example.\n", "29. Can you define functions inside functions? \n", "30. What is function closure in Python? How is it useful? Give an example.\n", "31. What is recursion? Illustrate with an example.\n", "32. Can functions accept other functions as arguments? Illustrate with an example.\n", "33. Can functions return other functions as results? Illustrate with an example.\n", "34. What are decorators? How are they useful?\n", "35. Implement a function decorator which prints the arguments and result of wrapped functions.\n", "36. What are some in-built decorators in Python?\n", "37. Can you invoke a function inside the body of another function? Give an example.\n", "38. What is the single responsibility principle, and how does it apply while writing functions?\n", "39. What some characteristics of well-written functions?\n", "40. Can you use if statements or while loops within a function? Illustrate with an example.\n", "41. Compare the use of lambda functions in sorted(), map(), filter(), reduce(), and accumulate() functions and their different use cases.\n", "42. Check out the use of command line arguments in Python using `sys.argv[]`, and `getopt.getopt()`\n", "43. Decorators can be thought of as functions which modify the functionality of another function. They help to make your code shorter and more \"Pythonic\". Search and write down sample code snippets to understand Decorators in Python." ] }, { "cell_type": "code", "execution_count": null, "id": "ea4d5f09", "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 }