Python One Line If Not None

To assign the result of a function get_value() to variable x if it is different from None, use the Walrus operator if tmp := get_value(): x = tmp within a single-line if block. The Walrus operator assigns the function’s return value to the variable tmp and returns it at the same time, so that you can check and assign it to variable x subsequently.

Problem: How to assign a value to a variable if it is not equal to None—using only a single line of Python code?

Example: Say, you want to assign the return value of a function get_value(), but only if it doesn’t return None. Otherwise, you want to leave the value as it is.

Here’s a code example:

import random


def get_value():
    if random.random()>0.5:
        return None
    return 1

# Naive approach:
x = 42
tmp = get_value()
if tmp != None:
    x = tmp
print(tmp)

While this works, you need to execute the function get_value() twice which is not optimal. An alternative would be to assign the result of the get_value() function to a temporary variable to avoid repeated function execution:

x = 42
temp = get_value()
if temp != None:
    x = temp
print(x)

However, this seems clunky and ineffective. Is there a better way?

Let’s have an overview of the one-liners that conditionally assign a value to a given variable:

Exercise: Run the code. Does it always generate the same result?

Method 1: Ternary Operator + Semicolon

The most basic ternary operator x if c else y consists of three operands x, c, and y. It is an expression with a return value. The ternary operator returns x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative y.

You can use the ternary operator to solve this problem in combination with the semicolon to write multiple lines of code as a Python one-liner.

# Method 1
tmp = get_value(); x = tmp if tmp else x

You cannot run the get_value() function twice—to check whether it returns True and to assign the return value to the variable x. Why? Because it’s nondeterministic and may return different values for different executions.

Therefore, the following code would be a blunt mistake:

x = get_value() if get_value() else x

The variable x may still be None—even after the ternary operator has seemingly checked the condition.

Related articles:

Method 2: Walrus + One-Line-If

A beautiful extension of Python 3.8 is the Walrus operator. The Walrus operator := is an assignment operator with return value. Thus, it allows you to check a condition and assign a value at the same time:

# Method 2
if tmp := get_value(): x = tmp

This is a very clean, readable, and Pythonic way. Also, you don’t have the redundant identity assignment in case the if condition is not fulfilled.

Related Article: The Walrus Operator in Python 3.8

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

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!!