Python – Truth values deletion in List

Due to the upcoming of Machine Learning, focus has now moved on handling the values than ever before, the reason behind this is that it is the essential step of data preprocessing before it is fed into further techniques to perform. Hence removal of values in essential, be it None, or sometimes Truth, and knowledge of it is a must. Lets discuss certain ways in which this is achieved.

Method #1 : Naive Method
In naive method, we iterate through whole list and append all the filtered, None values into a new list, hence ready to be performed with subsequent operations.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Truth values deletion in List
# using naive method 
  
# initializing list
test_list = [1, None, 4, None, False, 5, 8, False]
  
# printing original list 
print ("The original list is : " + str(test_list))
  
# using naive method 
# Truth values deletion in List
res = []
for val in test_list:
    if not val:
        res.append(val)
  
# printing result
print ("List after removal of Truth values : " + str(res))

chevron_right


Output :

The original list is : [1, None, 4, None, False, 5, 8, False]
List after removal of Truth values : [None, None, False, False]

 

Method #2 : Using list comprehension
The longer task of using the naive method and increasing line of codes can be done in compact way using this method. We just check for None values and construct the new filtered list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Truth values deletion in List
# using list comprehension
  
# initializing list
test_list = [1, None, 4, None, False, 5, 8, False]
  
# printing original list 
print ("The original list is : " + str(test_list))
  
# using list comprehension
# Truth values deletion in List
res = [i for i in test_list if not i]
  
# printing result
print ("List after removal of Truth values : " + str(res))

chevron_right


Output :

The original list is : [1, None, 4, None, False, 5, 8, False]
List after removal of Truth values : [None, None, False, False]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.