What Are Python Lambda Functions?

I learned python lambda functions from a codecademy.com tutorial – highly recommend.

My definition:

A one-liner for defining a function.

Example:

add_two = lambda x: x + 2

add_two(5) //prints 7

add_two(100) //prints 102

add_two(-2) //prints 0

Notes:

  • Similar to defining a function with keyword   def
  • The variable after keyword lambda is your input
  • Anything after the colon (:) is what you would be returning
  • Whatever variable you’re assigning the lambda function is the name of the function

Adding if… else statements to our lambda functions:

Template:

<WHAT TO RETURN IF STATEMENT IS TRUE> if <IF STATEMENT> else <WHAT TO RETURN IF STATEMENT IS FALSE>

Example:

check_if_a_grade = lambda grade: "Got an A!" if grade >= 90 else "Did not get an A…"

Notes:

  • Lambda functions only work as a one line command
  • Helpful if you’re going to use the function only once

More Examples:

contains_a = lambda word: True if 'a' in word else False

print(contains_a("banana")) //True

print(contains_a("apple")) //True

print(contains_a("cherry")) //False
long_string = lambda str: True if len(str) > 12 else False

print(long_string("short")) //False

print(long_string("photosynthesis")) //True
ends_in_a = lambda str: True if str[-1] == 'a' else False

print(ends_in_a("data")) //True

print(ends_in_a("aardvark")) //False
even_or_odd = lambda num: 'even' if num % 2 == 0 else 'odd'

print(even_or_odd(10)) //even

print(even_or_odd(5)) //odd
ones_place = lambda num: num % 10

print(ones_place(123)) //3, because 3 is in the one's place of 123

print(ones_place(4)) //4
How to Export Your Universal Analytics (GA3) Data the Fastest & Easiest Way [w/ Free Templates Included]
A Beginner Data Engineer Project: Extract Random Jokes via API with Python (Part 2)
A Beginner Data Engineer Project: Extract Random Jokes via API with Python (Part 1)
What Are Python Lambda Functions?
How to Make a BigQuery Real-Time MTD Job Cost Monitoring Dashboard (Part 1): Setting Up the Data
3 Things You Need to Get Paid More
How to Connect BigQuery with dbt
How to Model GA4 Data Easier in BigQuery with this Helpful Tool
When to Use IF NULL THEN 0 (How to Handle Null Values in SQL)
GA4 & BigQuery: A SQL Model for a Base Events Table (How to Unnest Fields)

Related Posts