How to Remove None Values from a List in Python?

Estimated read time 1 min read

To remove None values from a list in Python, you can use a list comprehension that filters out the None values. Here is an example code snippet that removes None values from a list:

original_list = [1, 2, None, 4, None, 6]

# Remove None values
new_list = [x for x in original_list if x is not None]

print(new_list)  # Output: [1, 2, 4, 6]

In this code, we define an original list (original_list) that contains None values.

Next, we create a new list (new_list) using a list comprehension that includes only the elements from the original list that are not None. The is not keyword is used to check if the element is not None.

Finally, we print the new list (new_list) that does not contain None values.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply