Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lab_lambda_functions [Odra Mathison] #7

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
291 changes: 291 additions & 0 deletions your-code/.ipynb_checkpoints/Learning-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,291 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Lambda Functions\n",
"\n",
"\n",
"Lesson Goals\n",
"\n",
"In this lesson you will learn all about lambda (or anonymous) functions and how they are used in Python.\n",
"Introduction\n",
"\n",
"Lambda functions are also called anonymous functions. What this means is that they are functions without a name. Lambda functions are typically short expressions. They can take multiple arguments but unlike functions, they can only have one expression.\n",
"Defining a Lambda Function\n",
"\n",
"For the most part, any lambda expression can also be written as a function (but not vice versa). When writing a lambda, we typically use the syntax of declaring a lambda and then listing the inputs of the lambda followed by a colon and then the expression.\n",
"\n",
"Let's look at an example of a lambda function and an equivalent function in Python below."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"25\n",
"25\n"
]
}
],
"source": [
"# Below is a lambda function that takes a number and returns its square\n",
"square = lambda x: x * x\n",
"\n",
"# Here we have a function that returns the same result as the lambda function\n",
"def square_function(x):\n",
" return x * x\n",
" \n",
"print (square(5))\n",
"print (square_function(5))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also pass multiple arguments to our lambda function."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"11"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"summarize = lambda a, b: a + b\n",
"\n",
"summarize(5, 6)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# If Statements in Lambda Functions\n",
"\n",
"If statements have a slightly different syntax in a lambda expression. Below is an example of a lambda expression that computes the fraction of two numbers unless the denominator is zero."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5\n",
"0\n"
]
}
],
"source": [
"div = lambda num, denom: num / denom if (denom != 0) else 0\n",
"\n",
"print (div(5, 10))\n",
"\n",
"print (div(10, 0))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As we can see in the lambda function above, we specify the if after we specify the action. We also do not use colons in the if statement.\n",
"\n",
"\n",
"# Lambdas in the Return Statement of a Function\n",
"\n",
"We can use lambda expressions to return a function from a function. Here is an example:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"range(0, 10)\n",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[0, 1, 2, 3, 4]\n"
]
}
],
"source": [
"def generate_range(lower):\n",
" return lambda upper: range(lower, upper)\n",
" \n",
"custom_range = generate_range(0)\n",
"\n",
"\n",
"\n",
"print (custom_range(10)) \n",
"print ([x for x in custom_range(10)])\n",
"print ([x for x in custom_range(5)])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Lambdas in List Comprehensions\n",
"\n",
"Lambdas are great when we want to generate a list in a quick and concise manner. We can apply the lambda expression to every element in the list and generate a new list.\n",
"\n",
"Here is an example of generating the squares of all numbers 1 through 10. We generate the numbers using the range function and square them using a lambda expression. "
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 4, 9, 16, 25, 36, 49, 64, 81]\n"
]
}
],
"source": [
"square = lambda x: x * x\n",
"squared = [square(x) for x in range(1, 10)]\n",
"\n",
"print(squared)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also use lambda functions to transform existing lists. Here we replace a dash with a space in a list of school subjects."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Calculus', 'Philosophy', 'Art History', 'Computer Science']\n"
]
}
],
"source": [
"school_dash = ['Calculus', 'Philosophy', 'Art-History', 'Computer-Science']\n",
"\n",
"school_space = [(lambda x: x.replace('-', ' '))(x) for x in school_dash]\n",
"\n",
"print(school_space)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Lambdas as Arguments in Functions\n",
"\n",
"Lambda functions really shine as arguments in functions. One example is sorting. Typically, we only sort using the default options in Python. However, we can define our own custom sorting lambda expression and pass that as an argument to the sorting function.\n",
"\n",
"In the example below we will sort by the last letter of the school subject. We will first create a lambda function that returns the last letter of the string and then sort using this function as a sorting key."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Computer Science', 'Calculus', 'Philosophy', 'Art History']"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"last = lambda x: x[-1]\n",
"\n",
"sorted(school_space, key=last)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As we can see, we sorted by the last letter of each string.\n",
"Advantages and Disadvantages of Lambda Functions\n",
"\n",
"Lambda functions have several advantages but also some disadvantages.\n",
"\n",
"Advantages:\n",
"\n",
" Lambda functions are concise since they only contain one expression.\n",
" Lambda can be passed around without a variable (hence why they are considered anonymous).\n",
" Lambda functions return automatically.\n",
"\n",
"Disadvantages:\n",
"\n",
" Sometimes lambda functions can over-complicate and it would be better to use a regular function instead. Particularly, when the expression is complex and may benefit from being separated into multiple lines.\n",
" They use different syntax (for example, if statements have different syntax in lambda functions).\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"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.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Loading