A None keyword is used in Python to denote a null value, a not available value, or no value at all. When constructing lists programmatically we will end up creating lists containing None values.
Consider the list:
This list has 2 None values that we wish to remove. Note that None is not enclosed in quotes (if that were to be done, it would be considered a regular string). There are at least four ways to do so. Lets learn them!
Method 1: The naive way - use a for loop
The naive way to do it is likely the first that comes to mind. We write a for loop iterating through each element of the list and construct a new list containing only the non-None values:
Here we have created a new variable called “newlist” which is initialized to the empty list. Then we cycle through every element of “mylist” and it is not None, we append it to the newlist. Finally, we print the newlist. The output is:
Method 2: Use a list comprehension
A list comprehension is a more elegant way to achieve this leading to more succinct Python-y code:
Here we are adding each “x” from “mylist” to constitute newlist as long as it is not None. The output is the same as before:
Method 3: Use a filter function
The third approach we will present uses a filter function. Filter takes two arguments: a function that is used as the filtering function and the list. Because we wish to retain list entries that are not None, the filter function checks if the values are not None. The output of the filter needs to be converted into a list hence the list constructor:
The output is the same as before:
Method 4: Use itertools.filterfalse()
The final method we will use employs the itertools module and the filterfalse method within it:
The signature of the filterfalse() function in itertools is very similar to the built-in filter() function but the semantics are different. Note that unlike the previous example, the first argument to the filterfalse() function is a lambda function that checks for entries that you want to remove (not the ones you want to retain). This is a key semantic difference between these two functions. The output is:
There you have it - four different ways to remove the nuisance None values from your list. Which one is your favorite?
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.