Home » Python » Python programs

Remove falsy values from a list in Python

Here, we are going to learn how to remove falsy values from a list in Python programming language?
Submitted by IncludeHelp, on March 30, 2020

In python, the values that evaluate to False are considered Falsy values. The values are False, None, 0 and "".

Here, we are implementing a python program to remove the falsy values from a string. To remove these values we are using filter() method, it will filter out the falsy values.

Example:

    Input:
    [10, 20, 0, 30, 0, None]

    Output:
    [10, 20, 30]

    Input: 
    [False, None, 0, "", "Hello", 10, "Hi!"]
    
    Output: 
    ['Hello', 10, 'Hi!']

Program:

# Remove falsy values from a list in Python 
def newlist(lst):
  return list(filter(None, lst))

# main code
list1 = [10, 20, 0, 30, 0, None]
list2 = [40, False, "Hello", "", None]
list3 = [False, None, 0, "", "Hello", 10, "Hi!"]

# printing original strings
print("list1: ", list1)
print("list2: ", list2)
print("list3: ", list3)

# removing falsy values and printing
print("newlist(list1): ", newlist(list1))
print("newlist(list2): ", newlist(list2))
print("newlist(list3): ", newlist(list3))

Output

list1:  [10, 20, 0, 30, 0, None]
list2:  [40, False, 'Hello', '', None]
list3:  [False, None, 0, '', 'Hello', 10, 'Hi!']
newlist(list1):  [10, 20, 30]
newlist(list2):  [40, 'Hello']
newlist(list3):  ['Hello', 10, 'Hi!']





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.