├── .DS_Store ├── README.md └── Elements of Functional Programming in Python.ipynb /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/parulnith/Elements-of-Functional-Programming-in-Python/HEAD/.DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Elements of Functional Programming in Python 2 | 3 | [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/parulnith/Elements-of-Functional-Programming-in-Python/master) 4 | 5 | ![](https://cdn-images-1.medium.com/max/800/1*TOsk9zG2gpYmf5d2JmIcUA.png) 6 | 7 | Just like there are multiple programming languages in the world, in the same way, there are innumerable categories in which they can be classified. A programming paradigm is one such way which tries to classify programming languages based on their features or coding style. A programming paradigm is essentially a style or a way of programming. 8 | Most of the times we understand Python as an object-oriented language, where we model our data in the form of classes, objects, and methods. However, there exist several alternatives to OOP and functional programming is one of them. 9 | 10 | ## Objective 11 | This is the repository linked to the tutorial with the same name. The idea is to introduce people to the concept of Functional Programming in Python using functions like Map, Filter, Reduce and Lambda. 12 | 13 | ## Blogpost 14 | [Elements of Functional Programming in Python](https://medium.com/p/1b295ea5bbe0/edit) 15 | 16 | ## Table Of Contents 17 | 18 | * Functional Programming(FP) 19 | * The Lambda Expression 20 | * The Map Function 21 | * The Filter Function 22 | * The Reduce Function 23 | * List Comprehensions: Alternative to map, filter and reduce 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Elements of Functional Programming in Python.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Elements of Functional Programming in Python\n", 8 | "Learn how to how to use the lambda, map, filter and reduce functions in Python to transform data structures." 9 | ] 10 | }, 11 | { 12 | "cell_type": "markdown", 13 | "metadata": {}, 14 | "source": [ 15 | "Python provides features like lambda, filter, map, and reduce that can basically cover most of what you would need to know about Functional Programming." 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": {}, 21 | "source": [ 22 | "For detailed analysis, please see the accompanying blog titled:**[Elements of Functional Programming in Python](https://medium.com/p/1b295ea5bbe0/edit)**" 23 | ] 24 | }, 25 | { 26 | "cell_type": "markdown", 27 | "metadata": {}, 28 | "source": [ 29 | "## The Lambda Expression" 30 | ] 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "metadata": {}, 35 | "source": [ 36 | "Lambda expressions - also known as \"anonymous functions\" - allow us to create and use a function in a single line. They are useful when we need a short function that will be used only once. \n", 37 | "\n", 38 | "They are mostly used in conjunction with the map, filter and the sort methods, which we will see later in the article.\n", 39 | "\n", 40 | "Let's write a function in Python, that will compute the value of 5x + 2. The standard approach would be to define a function." 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": 5, 46 | "metadata": {}, 47 | "outputs": [ 48 | { 49 | "data": { 50 | "text/plain": [ 51 | "17" 52 | ] 53 | }, 54 | "execution_count": 5, 55 | "metadata": {}, 56 | "output_type": "execute_result" 57 | } 58 | ], 59 | "source": [ 60 | "def f(x):\n", 61 | " \"\"\"Function to compute the value of 5x+2\"\"\"\n", 62 | " return 5*x+2\n", 63 | "f(3)" 64 | ] 65 | }, 66 | { 67 | "cell_type": "markdown", 68 | "metadata": {}, 69 | "source": [ 70 | "Now we would compute the same expression using Lambda functions. To create a lambda expression, we type in the keyword **lambda**, followed by the inputs. Next, we enter a colon followed by the expression that will be the return value." 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": 6, 76 | "metadata": {}, 77 | "outputs": [ 78 | { 79 | "data": { 80 | "text/plain": [ 81 | "(x)>" 82 | ] 83 | }, 84 | "execution_count": 6, 85 | "metadata": {}, 86 | "output_type": "execute_result" 87 | } 88 | ], 89 | "source": [ 90 | "lambda x: 5*x+2" 91 | ] 92 | }, 93 | { 94 | "cell_type": "markdown", 95 | "metadata": {}, 96 | "source": [ 97 | "This lambda function will take the input x and return 5x + 2, just like the earlier function f. There is a problem, however.The **lambda** is not the name of the function. It is a Python keyword that says - what follows is an anonymous function. So how do we use it? One way is to give it a name.\n", 98 | "Let us call this lambda expression **g**. Now, you can use this like any other function." 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": 7, 104 | "metadata": {}, 105 | "outputs": [ 106 | { 107 | "data": { 108 | "text/plain": [ 109 | "17" 110 | ] 111 | }, 112 | "execution_count": 7, 113 | "metadata": {}, 114 | "output_type": "execute_result" 115 | } 116 | ], 117 | "source": [ 118 | "g = lambda x: 5*x+2\n", 119 | "g(3)" 120 | ] 121 | }, 122 | { 123 | "cell_type": "markdown", 124 | "metadata": {}, 125 | "source": [ 126 | "### Lambda expression with multiple inputs." 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": 20, 132 | "metadata": {}, 133 | "outputs": [ 134 | { 135 | "data": { 136 | "text/plain": [ 137 | "2.215646837627989" 138 | ] 139 | }, 140 | "execution_count": 20, 141 | "metadata": {}, 142 | "output_type": "execute_result" 143 | } 144 | ], 145 | "source": [ 146 | "# Calculating Harmonic Mean using lambda function\n", 147 | "harmonic_mean = lambda x,y,z : 3/(1/x + 1/y + 1/z)**0.5\n", 148 | "harmonic_mean(1,2,3)" 149 | ] 150 | }, 151 | { 152 | "cell_type": "markdown", 153 | "metadata": {}, 154 | "source": [ 155 | "### Lambda expression without inputs.\n", 156 | "let's look at a common use of Lambda function where we do not assign it a name. Let's say we have a list of the first seven U.S Presidents and we'd like to sort this list by their last name. We shall create a Lambda function that extracts the last name, and uses that as the sorting value." 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 21, 162 | "metadata": {}, 163 | "outputs": [], 164 | "source": [ 165 | "# Sorting a List by thr last name using lambda expression" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": 22, 171 | "metadata": {}, 172 | "outputs": [ 173 | { 174 | "data": { 175 | "text/plain": [ 176 | "['John Adams',\n", 177 | " 'John Quincy Adams',\n", 178 | " 'Andrew Jackson',\n", 179 | " 'Thomas Jefferson',\n", 180 | " 'James Madison',\n", 181 | " 'James Monroe',\n", 182 | " 'George Washington']" 183 | ] 184 | }, 185 | "execution_count": 22, 186 | "metadata": {}, 187 | "output_type": "execute_result" 188 | } 189 | ], 190 | "source": [ 191 | "presidents_usa = [\"George Washington\", \"John Adams\",\"Thomas Jefferson\",\"James Madison\",\"James Monroe\",\"John Quincy Adams\",\"Andrew Jackson\"]\n", 192 | "\n", 193 | "presidents_usa.sort(key = lambda name: name.split(\" \")[-1].lower())\n", 194 | "presidents_usa" 195 | ] 196 | }, 197 | { 198 | "cell_type": "markdown", 199 | "metadata": {}, 200 | "source": [ 201 | "## The Map Function\n", 202 | "\n", 203 | "The **map** function applies a function to every item of iterable, yielding the results. When used with lists, Map transforms a given list into a new list by applying the function to all the items in an input_list.\n", 204 | "\n", 205 | "### Syntax\n", 206 | "```\n", 207 | "map(function_to_apply, iterables)\n", 208 | "```" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "metadata": {}, 214 | "source": [ 215 | "### Usage\n", 216 | "Suppose we have a function that computes the volume of a cube, given the value of its edge(a)" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": 25, 222 | "metadata": {}, 223 | "outputs": [], 224 | "source": [ 225 | "def volume(a):\n", 226 | " \"\"\"volumne of a cube with edge 'a'\"\"\"\n", 227 | " return a**3" 228 | ] 229 | }, 230 | { 231 | "cell_type": "markdown", 232 | "metadata": {}, 233 | "source": [ 234 | "What if we need to compute the volumes for many different cubes with different edge lengths? " 235 | ] 236 | }, 237 | { 238 | "cell_type": "code", 239 | "execution_count": 26, 240 | "metadata": {}, 241 | "outputs": [], 242 | "source": [ 243 | "# Edge length in cm\n", 244 | "edges = [1,2,3,4,5]" 245 | ] 246 | }, 247 | { 248 | "cell_type": "markdown", 249 | "metadata": {}, 250 | "source": [ 251 | "There are two ways to do this. One by using the `direct method` and the other by using the `map` function.\n" 252 | ] 253 | }, 254 | { 255 | "cell_type": "code", 256 | "execution_count": 27, 257 | "metadata": {}, 258 | "outputs": [ 259 | { 260 | "data": { 261 | "text/plain": [ 262 | "[1, 8, 27, 64, 125]" 263 | ] 264 | }, 265 | "execution_count": 27, 266 | "metadata": {}, 267 | "output_type": "execute_result" 268 | } 269 | ], 270 | "source": [ 271 | "# Calculating the volume of given cubes using Direct Method\n", 272 | "\n", 273 | "volumes = []\n", 274 | "for a in edges:\n", 275 | " v = volume(a)\n", 276 | " volumes.append(v)\n", 277 | " \n", 278 | " \n", 279 | "volumes" 280 | ] 281 | }, 282 | { 283 | "cell_type": "markdown", 284 | "metadata": {}, 285 | "source": [ 286 | "Now let's see how we can accomplish this task using a single line of code with the map function." 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": 29, 292 | "metadata": {}, 293 | "outputs": [ 294 | { 295 | "data": { 296 | "text/plain": [ 297 | "" 298 | ] 299 | }, 300 | "execution_count": 29, 301 | "metadata": {}, 302 | "output_type": "execute_result" 303 | } 304 | ], 305 | "source": [ 306 | "# Calculating the volume of given cubes using the Map function\n", 307 | "\n", 308 | "map(volume,edges)\n" 309 | ] 310 | }, 311 | { 312 | "cell_type": "markdown", 313 | "metadata": {}, 314 | "source": [ 315 | "The map function takes in two arguments. \n", 316 | "The first is a function, and the second is your list, tuple, or any other iterable object. Here, the map function applies the volume function to each element in the list. \n", 317 | "\n", 318 | "However, an important thing to note here is that the output of the map function is not a list but a map object, which is actually an iterator over the results. We can, however, turn this into a list by passing the map to the list constructor." 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "execution_count": 31, 324 | "metadata": {}, 325 | "outputs": [ 326 | { 327 | "data": { 328 | "text/plain": [ 329 | "[1, 8, 27, 64, 125]" 330 | ] 331 | }, 332 | "execution_count": 31, 333 | "metadata": {}, 334 | "output_type": "execute_result" 335 | } 336 | ], 337 | "source": [ 338 | "list(map(volume,edges))" 339 | ] 340 | }, 341 | { 342 | "cell_type": "markdown", 343 | "metadata": {}, 344 | "source": [ 345 | "### Example" 346 | ] 347 | }, 348 | { 349 | "cell_type": "markdown", 350 | "metadata": {}, 351 | "source": [ 352 | "Let's now see an example which demonstrates the use of `lambda` function with the `map` function. We have a list of tuples containing name and heights for 5 people. Each of the height is in centimeters and we need to convert it into feet.\n", 353 | "\n", 354 | "We will first write a converter function using a lambda expression which will accept a tuple as the input and will return a tuple with the same name." 355 | ] 356 | }, 357 | { 358 | "cell_type": "code", 359 | "execution_count": 32, 360 | "metadata": {}, 361 | "outputs": [ 362 | { 363 | "data": { 364 | "text/plain": [ 365 | "[('Tom', 6.0),\n", 366 | " ('Daisy', 5.6),\n", 367 | " ('Margaret', 5.9),\n", 368 | " ('Michael', 6.2),\n", 369 | " ('Nick', 5.4)]" 370 | ] 371 | }, 372 | "execution_count": 32, 373 | "metadata": {}, 374 | "output_type": "execute_result" 375 | } 376 | ], 377 | "source": [ 378 | "# Convert height from cms to feet : 1 cm = 0.0328 feet\n", 379 | "height_in_cms = [('Tom',183),('Daisy',171),('Margaret',179),('Michael',190),('Nick',165)]\n", 380 | "\n", 381 | "#Writing Convertor function using lambda expression\n", 382 | "height_in_feet = lambda data: (data[0],round(data[1]*0.0328,1))\n", 383 | "\n", 384 | "#Using the 'Map' function\n", 385 | "list(map(height_in_feet,height_in_cms))" 386 | ] 387 | }, 388 | { 389 | "cell_type": "markdown", 390 | "metadata": {}, 391 | "source": [ 392 | "## The Filter Function\n", 393 | "\n", 394 | "The `filter` function constructs an iterator from those elements of iterable for which function returns true. This means filter function is used to select certain pieces of data from a list, tuple, or other collection of data, hence the name.\n", 395 | "\n", 396 | "### Syntax\n", 397 | "\n", 398 | "```\n", 399 | "filter(filter(function, iterable)\n", 400 | "```" 401 | ] 402 | }, 403 | { 404 | "cell_type": "markdown", 405 | "metadata": {}, 406 | "source": [ 407 | "### Usage\n", 408 | "\n", 409 | "Let's see an example where we want to get the list of all numbers that are greater than 5, from a given input list." 410 | ] 411 | }, 412 | { 413 | "cell_type": "code", 414 | "execution_count": 33, 415 | "metadata": {}, 416 | "outputs": [ 417 | { 418 | "data": { 419 | "text/plain": [ 420 | "[6, 7, 8, 9]" 421 | ] 422 | }, 423 | "execution_count": 33, 424 | "metadata": {}, 425 | "output_type": "execute_result" 426 | } 427 | ], 428 | "source": [ 429 | "# Filter out all the numbers greater than 5 from a list\n", 430 | "\n", 431 | "my_list = [1,2,3,4,5,6,7,8,9]\n", 432 | "output_list = filter(lambda x : x>5, my_list)\n", 433 | "\n", 434 | "list(output_list)" 435 | ] 436 | }, 437 | { 438 | "cell_type": "markdown", 439 | "metadata": {}, 440 | "source": [ 441 | "### Example" 442 | ] 443 | }, 444 | { 445 | "cell_type": "markdown", 446 | "metadata": {}, 447 | "source": [ 448 | "Here is a list containing some of the countries in Asia. Notice there are numerous strings that are empty. We'll use the filter function to remove these missing values. We'll simply pass none as the first argument and the second argument is the list of data as before." 449 | ] 450 | }, 451 | { 452 | "cell_type": "code", 453 | "execution_count": 34, 454 | "metadata": {}, 455 | "outputs": [ 456 | { 457 | "data": { 458 | "text/plain": [ 459 | "['Afghanistan', 'Bhutan', 'China', 'Georgia', 'India']" 460 | ] 461 | }, 462 | "execution_count": 34, 463 | "metadata": {}, 464 | "output_type": "execute_result" 465 | } 466 | ], 467 | "source": [ 468 | "# Removing missing values from a list\n", 469 | "\n", 470 | "countries_asia = [\"Afghanistan\",\"\",\"Bhutan\",\"\",\"China\",\"\",\"Georgia\",\"\",\"\",\"India\"]\n", 471 | "\n", 472 | "list(filter(None,countries_asia))" 473 | ] 474 | }, 475 | { 476 | "cell_type": "markdown", 477 | "metadata": {}, 478 | "source": [ 479 | "This filters out all values that are treated as false in a boolean setting." 480 | ] 481 | }, 482 | { 483 | "cell_type": "markdown", 484 | "metadata": {}, 485 | "source": [ 486 | "## The Reduce Function\n", 487 | "\n", 488 | "The `Reduce` function is a bit unusual and in fact, as of Python 3, it is no longer a built-in function. Instead, it has been moved to the functools module. \n", 489 | "\n", 490 | "The 'reduce' function transforms a given list into a single value by applying a function cumulatively to the items of sequence, from left to right,\n", 491 | "\n", 492 | "### Syntax\n", 493 | "\n", 494 | "```\n", 495 | "reduce(func, seq)\n", 496 | "```\n", 497 | "where reduce continually applies the function func() to the sequence seq and returns a single value." 498 | ] 499 | }, 500 | { 501 | "cell_type": "markdown", 502 | "metadata": {}, 503 | "source": [ 504 | "### Usage\n", 505 | "Let's illustrate the working of the reduce function with the help of a simple example that computes the product of a list of integers." 506 | ] 507 | }, 508 | { 509 | "cell_type": "code", 510 | "execution_count": 36, 511 | "metadata": {}, 512 | "outputs": [ 513 | { 514 | "data": { 515 | "text/plain": [ 516 | "120" 517 | ] 518 | }, 519 | "execution_count": 36, 520 | "metadata": {}, 521 | "output_type": "execute_result" 522 | } 523 | ], 524 | "source": [ 525 | "# Compute the product of a list of integers using 'reduce'function\n", 526 | "\n", 527 | "from functools import reduce\n", 528 | "product = reduce((lambda x,y : x*y), [1,2,3,4,5])\n", 529 | "\n", 530 | "product" 531 | ] 532 | }, 533 | { 534 | "cell_type": "markdown", 535 | "metadata": {}, 536 | "source": [ 537 | "The following diagram shows the intermediate steps of the calculation:\n", 538 | "![](https://cdn-images-1.medium.com/max/800/1*tFi8CEmD3eAPwP3_nHWaTg.png)" 539 | ] 540 | }, 541 | { 542 | "cell_type": "markdown", 543 | "metadata": {}, 544 | "source": [ 545 | "The above program can also be written with an explicit for loop which is more clear.Hence Use functools.reduce if you really need it\n" 546 | ] 547 | }, 548 | { 549 | "cell_type": "code", 550 | "execution_count": 38, 551 | "metadata": {}, 552 | "outputs": [ 553 | { 554 | "data": { 555 | "text/plain": [ 556 | "120" 557 | ] 558 | }, 559 | "execution_count": 38, 560 | "metadata": {}, 561 | "output_type": "execute_result" 562 | } 563 | ], 564 | "source": [ 565 | "# Compute the product of a list of integers using a 'For' loop\n", 566 | "\n", 567 | "product = 1\n", 568 | "list = [1,2,3,4,5]\n", 569 | "for num in list:\n", 570 | " product = product*num\n", 571 | " \n", 572 | "product " 573 | ] 574 | }, 575 | { 576 | "cell_type": "markdown", 577 | "metadata": {}, 578 | "source": [ 579 | "### Example\n", 580 | "\n", 581 | "The `reduce` function can determine the maximum of a list containing integers in a single line of code. There does exist a built-in function called `max()` in Python which is normally used for this purpose as `max(list_name)`." 582 | ] 583 | }, 584 | { 585 | "cell_type": "code", 586 | "execution_count": 42, 587 | "metadata": {}, 588 | "outputs": [ 589 | { 590 | "data": { 591 | "text/plain": [ 592 | "698" 593 | ] 594 | }, 595 | "execution_count": 42, 596 | "metadata": {}, 597 | "output_type": "execute_result" 598 | } 599 | ], 600 | "source": [ 601 | "# Determining the maximum number in a given list\n", 602 | "\n", 603 | "from functools import reduce\n", 604 | "f = lambda a,b : a if (a>b) else b\n", 605 | "reduce(f,[58,69,12,158,698])" 606 | ] 607 | }, 608 | { 609 | "cell_type": "markdown", 610 | "metadata": {}, 611 | "source": [ 612 | "## List Comprehensions: Alternative to map, filter and reduce\n", 613 | "\n", 614 | "**List comprehension** is a way to define and create lists in Python. in most cases, list comprehensions let us create lists in a single line of code without worrying about initializing lists or setting up loops.\n", 615 | "It is also a substitute for the lambda function as well as the functions `map()`, `filter()` and `reduce()`. Some people find it a more pythonic way of writing functions and find it easier to understand." 616 | ] 617 | }, 618 | { 619 | "cell_type": "markdown", 620 | "metadata": {}, 621 | "source": [ 622 | "### Syntax" 623 | ] 624 | }, 625 | { 626 | "cell_type": "code", 627 | "execution_count": 44, 628 | "metadata": {}, 629 | "outputs": [ 630 | { 631 | "data": { 632 | "text/plain": [ 633 | "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]" 634 | ] 635 | }, 636 | "execution_count": 44, 637 | "metadata": {}, 638 | "output_type": "execute_result" 639 | } 640 | ], 641 | "source": [ 642 | "# Creating a list of squares of first 10 numbers using loops \n", 643 | "\n", 644 | "squares = []\n", 645 | "for x in range(10):\n", 646 | " squares.append(x**2)\n", 647 | " \n", 648 | "squares " 649 | ] 650 | }, 651 | { 652 | "cell_type": "markdown", 653 | "metadata": {}, 654 | "source": [ 655 | "Now let's use list comprehension to achieve the same result in a one liner" 656 | ] 657 | }, 658 | { 659 | "cell_type": "code", 660 | "execution_count": 45, 661 | "metadata": {}, 662 | "outputs": [ 663 | { 664 | "data": { 665 | "text/plain": [ 666 | "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]" 667 | ] 668 | }, 669 | "execution_count": 45, 670 | "metadata": {}, 671 | "output_type": "execute_result" 672 | } 673 | ], 674 | "source": [ 675 | "# # Creating a list of squares of first 10 using list comprehension\n", 676 | "\n", 677 | "squares = [x**2 for x in range(10)]\n", 678 | "squares\n" 679 | ] 680 | }, 681 | { 682 | "cell_type": "markdown", 683 | "metadata": {}, 684 | "source": [ 685 | "### Usage" 686 | ] 687 | }, 688 | { 689 | "cell_type": "markdown", 690 | "metadata": {}, 691 | "source": [ 692 | "Let's try and replicate the examples used in the above sections with list comprehensions." 693 | ] 694 | }, 695 | { 696 | "cell_type": "markdown", 697 | "metadata": {}, 698 | "source": [ 699 | "### List Comprehensions vs Map function\n", 700 | "\n", 701 | "We used map function in conjunction with the lambda function to convert a list of heights from cm to feet. Let's use list comprehensions to achieve the same results." 702 | ] 703 | }, 704 | { 705 | "cell_type": "code", 706 | "execution_count": 46, 707 | "metadata": {}, 708 | "outputs": [ 709 | { 710 | "data": { 711 | "text/plain": [ 712 | "[('Tom', 6.0),\n", 713 | " ('Daisy', 5.6),\n", 714 | " ('Margaret', 5.9),\n", 715 | " ('Michael', 6.2),\n", 716 | " ('Nick', 5.4)]" 717 | ] 718 | }, 719 | "execution_count": 46, 720 | "metadata": {}, 721 | "output_type": "execute_result" 722 | } 723 | ], 724 | "source": [ 725 | "# Convert height from cms to feet using List Comprehension : 1 cm = 0.0328 feet\n", 726 | "height_in_cms = [('Tom',183),('Daisy',171),('Margaret',179),('Michael',190),('Nick',165)]\n", 727 | "\n", 728 | "height_in_feet = [(height[0],round(height[1]*0.0328,1)) for height in height_in_cms]\n", 729 | "\n", 730 | "height_in_feet" 731 | ] 732 | }, 733 | { 734 | "cell_type": "markdown", 735 | "metadata": {}, 736 | "source": [ 737 | "### List Comprehensions vs Filter function\n", 738 | "\n", 739 | "We used the filter function to remove the missing values from a list of Asian countries. Let's use list comprehensions to get the same results." 740 | ] 741 | }, 742 | { 743 | "cell_type": "code", 744 | "execution_count": 47, 745 | "metadata": {}, 746 | "outputs": [ 747 | { 748 | "data": { 749 | "text/plain": [ 750 | "['Afghanistan', 'Bhutan', 'China', 'Georgia', 'India']" 751 | ] 752 | }, 753 | "execution_count": 47, 754 | "metadata": {}, 755 | "output_type": "execute_result" 756 | } 757 | ], 758 | "source": [ 759 | "# Removing missing values from a list\n", 760 | "\n", 761 | "countries_asia = [\"Afghanistan\",\"\",\"Bhutan\",\"\",\"China\",\"\",\"Georgia\",\"\",\"\",\"India\"]\n", 762 | "[country for country in countries_asia if country!=\"\"]" 763 | ] 764 | }, 765 | { 766 | "cell_type": "markdown", 767 | "metadata": {}, 768 | "source": [ 769 | "### List Comprehensions vs Reduce function\n", 770 | "\n", 771 | "Similarly, we can determine the maximum of a list containing integers easily using generator comprehension instead of using lambda and reduce. Generator expression are similar to list comprehension but with round brackets instead of the square one." 772 | ] 773 | }, 774 | { 775 | "cell_type": "code", 776 | "execution_count": 49, 777 | "metadata": {}, 778 | "outputs": [ 779 | { 780 | "data": { 781 | "text/plain": [ 782 | "956" 783 | ] 784 | }, 785 | "execution_count": 49, 786 | "metadata": {}, 787 | "output_type": "execute_result" 788 | } 789 | ], 790 | "source": [ 791 | "# Determining the maximum number in a given list\n", 792 | "\n", 793 | "numbers = [58,69,12,158,698,956]\n", 794 | "max((x) for x in numbers)" 795 | ] 796 | }, 797 | { 798 | "cell_type": "markdown", 799 | "metadata": {}, 800 | "source": [ 801 | "## References\n", 802 | "* [Don't Be Scared Of Functional Programming](https://www.smashingmagazine.com/2014/07/dont-be-scared-of-functional-programming/)\n", 803 | "* [Functional Programming HOWTO](https://docs.python.org/3.7/howto/functional.html)" 804 | ] 805 | }, 806 | { 807 | "cell_type": "code", 808 | "execution_count": null, 809 | "metadata": {}, 810 | "outputs": [], 811 | "source": [] 812 | } 813 | ], 814 | "metadata": { 815 | "kernelspec": { 816 | "display_name": "Python 3", 817 | "language": "python", 818 | "name": "python3" 819 | }, 820 | "language_info": { 821 | "codemirror_mode": { 822 | "name": "ipython", 823 | "version": 3 824 | }, 825 | "file_extension": ".py", 826 | "mimetype": "text/x-python", 827 | "name": "python", 828 | "nbconvert_exporter": "python", 829 | "pygments_lexer": "ipython3", 830 | "version": "3.7.3" 831 | } 832 | }, 833 | "nbformat": 4, 834 | "nbformat_minor": 2 835 | } 836 | --------------------------------------------------------------------------------