Return a default value if None in Python

avatar

Borislav Hadzhiev

Last updated: Jun 15, 2022

banner

Photo from Unsplash

Return a default value if None in Python #

Use a conditional expression to return a default value if None in Python, e.g. return "default value" if my_var is None else my_var. The conditional expression will return the default value if the variable stores None, otherwise the variable is returned.

main.py
# 👇️ return default value if variable is None def example(): my_var = None return "default value" if my_var is None else my_var print(example()) # 👉️ "default value" # --------------------------------------------- # 👇️ return default value if variable is None my_var = None my_var = "default value" if my_var is None else my_var print(my_var) # 👉️ default value

Conditional expressions are very similar to an if/else statement.

In the examples, we check if the variable stores None, and if it does, we return the string default value, otherwise the variable is returned.

You can use this approach to return a default value if None from a function, or to reassign a variable to a default value if it currently stores None.

An alternative approach is to use the boolean or operator.

main.py
# 👇️ return default value if variable is None def example(): my_var = None return my_var or "default value" print(example()) # 👉️ "default value" # --------------------------------------------- # 👇️ return default value if variable is None my_var = None my_var = my_var or "default value" print(my_var) # 👉️ "default value"

The expression x or y returns the value to the left if it's truthy, otherwise the value to the right is returned.

main.py
# 👇️ default value print(None or 'default value') # 👇️ hello print('hello' or 'default value')

However, this approach does not explicitly check for None.

The boolean or operator will return the value to the right if the value to the left is falsy.

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

So if the value to the left is any of the aforementioned falsy values, the value to the right is returned.

main.py
print(0 or 'default value') # 👉️ default value print("" or 'default value') # 👉️ default value

This might or might not suit your use case.

If you only want to check for None, use the conditional expression from the first code snippet.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.