Skip to content
Related Articles

Related Articles

Improve Article

Remove falsy values from a list in Python

  • Last Updated : 03 Jan, 2021

Prerequisite: Truthy vs Falsy Values in Python

In Python, the value that evaluates to False is considered as a Falsy value. The value such as empty list, empty dictionary, empty tuple, empty set, empty string, None, False, 0 are considered as Falsy values. So our task is to remove all the Falsy values from the List.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Examples:



Input:  [10,20,30,0,False,40,0]
Output:  [10,20,30,40]

Input: [False,None,1,2,3,"Geeks"]
Output: [1,2,3,"Geeks"]

Input: [[],(),"GeeksForGeeks",26,27]
Output: ["GeeksForGeeks",26,27]

Method 1 :

We can create a new list that will contain values that are not Falsy. We will iterate over the list, and check whether the given value is Truthy or Falsy. If it is Truthy we will add it to the new list. Now to check whether the given value is Truthy or Falsy, we can use bool() method. This method returns True if the value is Truthy else return False.

Python3




# Python Program to remove falsy values
# from List
  
# Function returning the updated list 
def Remove_Falsy(List):
    List1 = []
    for i in List:
        if(bool(i)):
            List1.append(i)
    return List1;
              
# Original List
List1 = [10, 20, 30, 0, False, 40, 0]
List2 = [False, None, 1, 2, 3, "Geeks"]
List3 = [[], (), "GeeksForGeeks", 26, 27]
  
# printing the updated list after removing Falsy values
print("List1[] = ", Remove_Falsy(List1))
print("List2[] = ", Remove_Falsy(List2))
print("List3[] = ", Remove_Falsy(List3))

Output:

List1[] =  [10, 20, 30, 40]
List2[] =  [1, 2, 3, 'Geeks']
List3[] =  ['GeeksForGeeks', 26, 27]

Method 2 : 

We can use the filter() method to filter out falsy values. In the method – filter(function,sequence) , we will use bool() method as an argument in the filter method .It will return true or false based upon truthy or falsy values.

Python3




# Python Program to remove falsy values
# from List
  
# Function returning the updated list 
def Remove_Falsy(List):
    return list(filter(bool,List))
  
# Original List
List1 = [ 10, 20, 30, 0, False, 40, 0]
List2 = [ False, None, 1, 2, 3, "Geeks"]
List3 = [ [], (), "GeeksForGeeks", 26, 27]
  
# printing the updated list after removing Falsy values
print("List1[] = ", Remove_Falsy(List1))
print("List2[] = ", Remove_Falsy(List2))
print("List3[] = ", Remove_Falsy(List3))

Output:

List1[] =  [10, 20, 30, 40]
List2[] =  [1, 2, 3, 'Geeks']
List3[] =  ['GeeksForGeeks', 26, 27]



My Personal Notes arrow_drop_up
Recommended Articles
Page :