Gabe Tao
Gabe Tao's blog


Gabe Tao's blog

Streamline your Python coding with one-liners

Streamline your Python coding with one-liners

Less is more

Gabe Tao's photo
Gabe Tao
·Jun 10, 2022·

6 min read

Table of contents

  • 1. One-line if statements
  • 2. List comprehension (One line for loop)
  • 3. Lambda functions
  • 4. Variable assignment
  • Final thoughts

Compared to languages like Java and C, Python is famous for letting you complete the same task in less lines of code. As Python develops and new versions are introduced, more methods of shrinking down your code while still making it readable are being made available. Here are a few ways of rewriting simple programs, shrinking them down to a single line of code. You'll be amazed at what Python can do!

1. One-line if statements

Typically, you'd write a simple conditional if block like this:

if age >= 16:
    print("Can drive")

Python lets you compress this into the following:

print("Can drive" if age >= 16)

If you want to add an else category, just add it onto the end:

print("Can drive" if age >= 16 else "Cannot drive")

Note that the block inside print() only returns a value, it doesn't actually execute the code like the first example does. The conditional must be placed inside a function or assigned to a variable.

You can even do the same with if-elif-else blocks. It's read differently than the normal multi-line syntax but still works the same way:

print("Drive + vote" if age >= 18 else "Drive" if age >= 16 else "Nothing")

Another way of writing the if statement is using the same syntax as before but just removing the newline:

if age >= 16: print("Can drive")

2. List comprehension (One line for loop)

List comprehension is probably the singular most important thing I've learned about Python in the past year or so (I feel guilty for not using this early enough). It lets you generate lists in a single-line for loop.

A normal for loop might look like this:

squares = []
for i in range(10): 
    squares[i] = i ** 2

With list comprehension, you can generate the list of squares like so:

squares = [i ** 2 for i in range(10)]

It's harder to understand than the one-line if, but the basic syntax goes like this:
[ do something to i for i in iterable ]. It's a powerful and concise way to create lists from iterables, like that generated by range().

Wait! It gets even better. By combining list comprehension with the one-line if statements, you can compress even more lines of code into one:

# Generate every other square number
squares = []
for i in range(10):
    if i % 2 == 0:
        squares[i] = i ** 2


squares = [i ** 2 for i in range(10) if i % 2 == 0]

Use an if-elif-else for even longer list comprehension - you have to place the conditionals before the loop (Line breaks for readability):

numbers = ["Divisible by 2" if i%2 == 0 \
           else "Divisible by 3" if i%3 == 0 \
           else "Not divisible by 2 or 3" \
           for i in range(100)]

3. Lambda functions

The lambda keyword lets you define a small anonymous function in a single line. Example:

func = lambda x: x + 5

On the left side of the colon are the argument(s) to the function and the right side is what the function returns. func now holds a function definition and can be called like normal.

>>> func(3)

You can also have multiple arguments in a lambda function, separated by commas, but multiple return values must be in a tuple.

>>> math_operations = lambda x, y: (x+y, x-y, x*y, x/y)
>>> math_operations(5, 10)
(15, -5, 50, 0.5)

Recursive lambda functions can be super useful. Here's an example of lambda being used to find a number in the Fibonacci sequence, coupled with a one-line if statement:

fibonacci = lambda x: None if x < 0 else x if x <=1 else fibonacci(x-2) + fibonacci(x-1)

Variable numbers of arguments with *args or **kwargs can also be used in the same way as def with lambda.

# Add all numbers given to a function (advanced)
>>> add = lambda *args, total=0: [(total := total + args[i]) for i in range(len(args))][-1]
>>> add(1, 2, 3, 4, 5)

4. Variable assignment

Instead of using multiple lines to assign several variables values, you can combine them into a single line using commas.

x = 1
y = 2
z = 3
# becomes
x, y, z  = 1, 2, 3

Swapping the contents of two or more variables, unlike low-level programming languages, is made easy:

temp = x
x = y
y = temp
# becomes
x, y = y, x

If you need to toggle the value of a variable, you can use some handy logic and math tricks to help you out:

# Toggle between True and False
x = not x

# Toggle between 1 and 2
x = 3 - x

# Toggle between strings
x = "apple"
t = {"apple": "banana", "banana": "apple"}
x = t[x]  # "banana"
x = t[x] # "apple"

Here's an advanced example. With the help of lambda functions and some variable arguments, you can toggle between any number of arbitrary items.

# Toggle between arbitrary pieces of data using lambda
t = [42, "apple", 3.14159, False]
toggle = lambda x, *args: args[(args.index(x) + 1) % len(args)]

x = 42
x = toggle(x, *t) # "apple"
x = toggle(x, *t) # 3.14159
x = toggle(x, *t) # False
x = toggle(x, *t) # 42

Final thoughts

To finish things off, here's a super-crazy one-liner that uses lambda, list comprehension, several one-line if statements, and other advanced techniques in order to tell you whether a number is prime or not.

>>> prime = lambda num: "Yes" if num > 1 and len((divisors := [str(d) for d in range(2, num-1) if (num%d == 0)])) == 0  else f"No, divisors are {', '.join(divisors)}"
>>> prime(17)
>>> prime(41)
>>> prime(51)
'No, divisors are 3, 17'
>>> prime(1000)
'No, divisors are 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500'

It gets the job done and works just as well as a 10-line program would... but it's not the cleanest or the most readable. One-liners might not always be the solution to every problem, especially in situations where other people are reading, editing, or trying to understand your code. Sometimes, writing out the full loop or function is the right thing to do, unless you're like me and just want the satisfaction of squeezing as much as possible into a single line. :)

That's all the one-liners I have for today - if you know any useful ones, comment below and let me know. I'm finding more and more places in my own code to use one-liners, and I feel like I'm just beginning to scratch the surface of what I can do with Python. Thanks for reading!

Did you find this article valuable?

Support Gabe Tao by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
Share this