Member-only story
What Are Python Lambda Functions, Anyway?
Learn to write Python like the pros by using lambda functions
Learning Python Takes Time
Traveling the road from rookie to Pythonista can take a while and varies from person to person. Most people start learning Python by reviewing the basic data structures for numbers, Booleans and strings, and then move to complex data structures like lists and dictionaries. From there you learn loops and if/else control logic, and eventually learn to write reusable code via functions.
Once you start exploring functions, you’ll come across lambda functions which can seem pretty intimidating at first. Similarly to list comprehensions, lambda functions allow you to write succinct code. Often something that would take several lines as a defined function can be done in one line using a lambda function!
Reviewing Python Functions
Typical Python functions are simply a self-contained set of instructions designed to perform a specific task. They are important to master and understand because they allow us to keep code organized by breaking it into smaller, reusable chunks. If we’re writing a large program, utilizing functions can make the code easier to read and debug too.
In Python, we define a function using the def keyword, then give the function a name along with any necessary arguments that impact the function body’s execution. Often times, the return keyword is used to terminate the function and return the desired output to whatever called the function. Here is an example function:
#python example function
def my_function(string):
return print(string)
The example my_function
takes a string as an argument and prints the string as the returned output.
What Is A Lambda Function?
To take your Python skills to the next level, you need to master both normal functions and lambda functions. Lambda functions are great for making code shorter and more concise, which is the way of the Pythonista! We’ll take a look at a few simple examples to review the syntax, and then look at some actual use cases for lambda functions that will make you look like a pro.