{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Lambda Functions\n", "Anonymous, single-use, or throw-away functions. \n", "**lambda arguments : expression** \n", "Here are some single-argument lambdas:" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "12\n" ] } ], "source": [ "add5 = lambda x: x + 5\n", "print(add5(7))" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "64\n" ] } ], "source": [ "square = lambda x: x * x\n", "print(square(8))" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "3\n" ] } ], "source": [ "get_tens = lambda p: int(p/10)%10\n", "print(get_tens(749))\n", "print(get_tens(836.21))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Lambdas as an argument in other functions** \n", "One of the most popular uses for lambda functions is as an argument inside sort, or filter functions. \n", "### Sorting a List of Tuples using Lambda" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[('carrots', 1.1), ('peaches', 2.45), ('eggs', 5.25), ('honey', 9.7)]\n" ] } ], "source": [ "list1 = [('eggs', 5.25), ('honey', 9.70), ('carrots', 1.10), ('peaches', 2.45)]\n", "list1.sort(key = lambda x: x[1])\n", "print(list1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Sorting a List of Dictionaries using Lambda" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[{'make': 'Tesla', 'model': 'X', 'year': 1999},\n", " {'make': 'Mercedes', 'model': 'C350E', 'year': 2008},\n", " {'make': 'Ford', 'model': 'Focus', 'year': 2013}]\n" ] } ], "source": [ "import pprint as pp\n", "list1 = [{'make':'Ford', 'model':'Focus', 'year':2013}, {'make':'Tesla', 'model':'X', 'year':1999}, {'make':'Mercedes', 'model':'C350E', 'year':2008}]\n", "list2 = sorted(list1, key = lambda x: x['year'])\n", "pp.pprint(list2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Filtering a List of Integers using Lambda" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 4, 6]\n" ] } ], "source": [ "list1 = [1, 2, 3, 4, 5, 6]\n", "list2 = list(filter(lambda x: x%2 == 0, list1))\n", "print(list2)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 3, 5]\n" ] } ], "source": [ "odds = lambda x: x%2 == 1\n", "list1 = [1, 2, 3, 4, 5, 6]\n", "list2 = list(filter(odds, list1))\n", "print(list2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Lambda Function on a List using Map\n", "Python's map function applies the lambda to every element in the list." ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 4, 9, 16, 25, 36]\n" ] } ], "source": [ "list1 = [1, 2, 3, 4, 5, 6]\n", "list2 = list(map(lambda x: x ** 2, list1))\n", "print(list2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Lambda Conditionals\n", "**lambda args: a if boolean_expression else b** " ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "starts_with_J = lambda x: True if x.startswith('J') else False\n", "print(starts_with_J('Joey'))" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "and\n" ] } ], "source": [ "wordb4 = lambda s, w: s.split()[s.split().index(w)-1] if w in s else None\n", "sentence = 'Four score and seven years ago'\n", "print(wordb4(sentence, 'seven'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Lambdas on DataTime Objects\n", "You sometimes want to get just the year, month, date or time for comparision. \n", "This would typically be most useful as a parameter in sort or filter functions." ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2019-03-07 19:36:58.442863\n", "2019\n" ] } ], "source": [ "import datetime\n", "\n", "now = datetime.datetime.now()\n", "print(now)\n", "year = lambda x: x.year\n", "print(year(now))" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4096\n", "125\n" ] } ], "source": [ "def do_something(f, val):\n", " return f(val)\n", "\n", "func = lambda x: x**3\n", "print(func(16))\n", "print(do_something(func, 5))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Extreme Lambdas\n", "This is probably a stretch -- you shouldn't be trying to do this much with Lambdas. \n", "Some things are better done in a regular function. But this shows what's possible with Lambdas." ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n", "False\n", "False\n", "True\n", "-1\n", "-21.67 \n" ] } ], "source": [ "isnum = lambda q: q.replace('.','',1).isdigit()\n", "print(isnum('25983'))\n", "print(isnum('3.1415'))\n", "print(isnum('T57'))\n", "print(isnum('-16'))\n", "\n", "is_num = lambda r: isnum(r[1:]) if r[0]=='-' else isnum(r)\n", "print(is_num('-16.4'))\n", "\n", "tonum = lambda s: float(s) if is_num(s) else -1\n", "print(tonum('30y'))\n", "print(tonum('-21.67'), type(tonum('-21.67')))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.0" } }, "nbformat": 4, "nbformat_minor": 2 }