A lambda function allows you to define a function in a single line. It starts with the keyword lambda
, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example, lambda x, y: x+y
calculates the sum of the two argument values x+y
in one line of Python code.
Problem: How to define a function in a single line of Python code?
Example: Say, you’ve got the following function in three lines. How to compress them into a single line of Python code?
def say_hi(*friends): for friend in friends: print('hi', friend) friends = ['Alice', 'Bob', 'Ann'] say_hi(*friends)
The code defines a function say_hi
that takes an iterable as input—the names of your friends—and prints 'hi x'
for each element x
in your iterable.
The output is:
''' hi Alice hi Bob hi Ann '''
Let’s dive into the different methods to accomplish this! First, here’s a quick interactive overview to test the waters:
Exercise: Run the code—is the output the same for all four methods?
Next, you’ll learn about each method in greater detail!
Method 1: Lambda Function
You can use a simple lambda function to accomplish this.
A lambda function is an anonymous function in Python. It starts with the keyword lambda
, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example, lambda x, y, z: x+y+z
would calculate the sum of the three argument values x+y+z
.
friends = ['Alice', 'Bob', 'Ann'] # Method 1: Lambda Function hi = lambda lst: [print('hi', x) for x in lst]
In the example, you want to print a string for each element in an iterable—but the lambda function only returns an object. Thus, we return a dummy object: a list of None
objects. The only purpose of creating this list is to execute the print() function repeatedly, for each element in the friends
list.
You obtain the following output:
hi(friends) ''' hi Alice hi Bob hi Ann '''
Method 2: Function Definition
A similar idea is employed in this one-liner example—but instead of using a lambda function, we define a regular function and simply skip the newline. This is possible if the function body has only one expression:
friends = ['Alice', 'Bob', 'Ann'] # Method 2: Function Definition def hi(lst): [print('hi', x) for x in lst]
The output is the same as before:
hi(friends) ''' hi Alice hi Bob hi Ann '''
This approach is more Pythonic than the first one because there’s no throw-away return value and it’s more concise.
Method 3: exec()
The third method uses the exec()
function. This is the brute-force approach to one-linerize any multi-liner!
To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character '\n'
and pass the result into the exec(...)
function. You can run this script from the outside (command line, shell, terminal) by using the command python -c "exec(...)"
.
We can apply this technique to the first example code snippet (the multi-line function definition) and rename the variables to make it more concise:
friends = ['Alice', 'Bob', 'Ann'] # Method 3: exec() exec("def hi(*lst):\n for x in lst:\n print('hi', x)\nhi(*friends)")
If you run the code, you’ll see the same output as before:
hi(friends) ''' hi Alice hi Bob hi Ann '''
This is very hard to read—our brain cannot grasp the whitespaces and newline characters easily. But I still wanted to include this method here because it shows how you or anyone else can compress complicated algorithms in a single line of Python code!
Watch the video if you want to learn more details about this technique:
Programmer Humor

Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Get your Python One-Liners on Amazon!!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.