Python one line function guide
This tutorial shows you examples of how to create a one line function in practice.
1. Writing function header and body in one line
Although indentations matter in Python, you can compress a function into a single line by writing the function body next to the colon ( : ) symbol:
Let’s see an example. Suppose you have a function as follows:
You can turn it into a one line function as follows:
But please note that you can’t use this one liner if you have a control flow in your function, such as for and if-else statements.
Suppose you have a function that prints out a list as follows:
Then using this syntax causes an error:
You can’t put a for or if statement next to the colon ( : ) symbol. You need to use a list comprehension to get a for loop in one line.
The above function prints the items in the list and returns a list filled with None . The returned list is simply ignored in this case.
Still, this syntax is limited and unpythonic. Python conventions generally discourage multiple statements per line and the maximum line length is 79 characters.
Another approach to create a one line Python function is to use a lambda function. Let’s learn how to do it next.
2. Using a lambda function
A lambda function is an anonymous function intended to be an inline parameter of another function.
But this function can also be used to create a function and assign it to a variable. Here’s a simple example:
As you can see, the greet variable effectively becomes a function, and you actually create a one line function that doesn’t violate Python’s PEP 8 style guide.
But keep in mind that a lambda function can’t have a for loop in its body. Suppose you create a lambda that accepts a list and prints it as follows:
You’ll have an invalid syntax error. To print a list, you need to use a list comprehension in the lambda function as follows:
However, I think the syntax is confusing because lambda is intended for simple, short functions.
Unless you have to create the function in one line, writing a regular function with the def keyword is preferable.
Conclusion
In Python, you can create a one line function by defining the function body next to the header or using a lambda function. Both methods are severely limited as you can’t include a for or if statement in the function.
One liner functions are good only for the simplest functions because the line breaks and indents in Python are designed to make your code clear and easy to comprehend.
I hope this tutorial is helpful. I’ve also written additional tutorials on Python one liners:
And that’s it for this tutorial. Until next time! 🙏
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
3 (Not So) Pythonic Ways to Define a Function in One Line [for Hackers]
Summary: The most Pythonic way to define a function in a single line is to (1) create an anonymous lambda function and (2) assign the function object to a variable name. You can then call the function by name just like any other regularly-defined function. For example, the statement f = lambda x: x+1 creates a function f that increments the argument x by one and returns the result: f(2) returns 3 .
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.
- 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.
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.
Be on the Right Side of Change 🚀
- The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
- Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
- Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.
Learning Resources 🧑💻
⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!
Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.
New Finxter Tutorials:
Finxter Categories: