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:
Problem: How to define a function in a single line of Python code? This article explores this mission-critical question in all detail!
Example: Say, you want to write the following function in a single line of code:
def f(x): return str(x * 3) + '!' print(f(1)) # 3! print(f('python')) # pythonpythonpython!
Let’s get a quick overview of how to accomplish this first:
Exercise: Change the one-liner functions to return the uppercase version of the generated string using the
string.upper() function. Then run the code to see if your output is correct!
Method 1: Single-Line Definition
The first and most straightforward way of defining a function in a single line is to just remove the line break:
def f1(x): return str(x * 3) + '!' print(f1(1)) print(f1('python'))
The function definition is identical to the original one with one difference: you removed the new line and the indentation from the definition. While this works for functions with single-line function bodies, you can easily extend it by using the semicolon as a separator:
>>> def fxx(): x=1; x=2; return x >>> fxx() 2
Sure, readability gets hurt if you’re doing this but you should still know the syntax in case you see code like this in a practical code project (you will)!
Method 2: Lambda Function
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
Here’s the most Pythonic way to write a function in a single line of code:
f2 = lambda x: str(x * 3) + '!' print(f2(1)) print(f2('python'))
You create a lambda function and assign the new function object to the variable
f2. This variable can now be used like any other function name defined in a regular function definition.
Method 3: exec()
Now, let’s get as unpythonic as we can get, shall we? The
exec() function takes one string as an argument. It then executes the code defined in the string argument. In combination with the multi-line character
'\n', this enables you to run all complicated multi-line code snippets in a single line. Hackers often use this technique to cram malicious scripts in a seemingly harmless single line of Python code. Powerful, I know.
# Method 3: exec() f3 = "def f(x):\n return str(x * 3) + '!'" exec(f3 + '\nprint(f(1))') exec(f3 + "\nprint(f('python'))")
f3 contains a two-line function definition of our original function
f. You then concatenate this string with a new line to print the result of running this newly created function in your script by passing arbitrary arguments into it.
Is it possible to write the if-then-else statement in a single line of code?
Yes, you can write most if statements in a single line of Python using any of the following methods:
- Write the if statement without else branch as a Python one-liner:
if 42 in range(100): print("42").
- If you want to set a variable, use the ternary operator:
x = "Alice" if "Jon" in "My name is Jonas" else "Bob".
- If you want to conditionally execute a function, still use the ternary operator:
print("42") if 42 in range(100) else print("21").
Python One-Liners Book
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 tips and tricks, regular expressions, machine learning, core data science topics, and 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.