Replace None values in a List in Python

avatar

Borislav Hadzhiev

Last updated: Jun 15, 2022

banner

Photo from Unsplash

Replace None values in a List in Python #

Use a list comprehension to replace None values in a list in Python, e.g. new_list_1 = ['' if i is None else i for i in my_list]. The list comprehension should return a different value, e.g. an empty string or 0 if the list item is None, otherwise it should return the list item.

main.py
my_list = ['a', None, 'b', None, 'c', None, None] # 👇️ replace None values in a list with empty string new_list_1 = ['' if i is None else i for i in my_list] print(new_list_1) # 👉️ ['a', '', 'b', '', 'c', '', ''] # 👇️ replace None values in a list with 0 new_list_1 = [0 if i is None else i for i in my_list] print(new_list_1) # 👉️ ['a', 0, 'b', 0, 'c', 0, 0]

The first example replaces None values in a list with an empty string, and the second replaces None with 0.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

We basically iterate over the list and return an empty string if the item of the current iteration is None, otherwise we return the item as is.

You can use this approach to replace None values with any other value.

Alternatively, you can use a for loop to replace None values in a list.

main.py
my_list = ['a', None, 'b', None, 'c', None, None] for index, item in enumerate(my_list): if item is None: my_list[index] = '' # 👈️ replaces None with empty string print(my_list) # 👉️ ['a', '', 'b', '', 'c', '', '']

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index, and the second, the item.

main.py
my_list = ['apple', 'banana', 'melon'] for index, item in enumerate(my_list): print(index, item) # 👉️ 0 apple, 1 banana, 2 melon

On each iteration, we check if the item is None, and if it is, we update the list item at the specific index.

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.