Q:

Remove falsy values from a list in Python

0

In python, the values that evaluate to False are considered Falsy values. The values are FalseNone0 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!']

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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!']

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now