w3resource

Python: Remove None value from a given list using lambda function

Python Lambda: Exercise-52 with Solution

Write a Python program to remove None values from a given list using the lambda function.

Sample Solution:

Python Code :

# Define a function 'remove_none' that filters out None values from a list
def remove_none(nums):
    # Use the 'filter' function with a lambda function to filter out elements that are not None
    # 'filter' returns an iterator, so convert it back to a list to get the result
    result = filter(lambda v: v is not None, nums)
    
    # Return the filtered list without the None values
    return list(result)

# Create a list 'nums' containing integers and some None values
nums = [12, 0, None, 23, None, -55, 234, 89, None, 0, 6, -12]

# Print the original list 'nums'
print("Original list:")
print(nums)

# Remove None values from the list using the 'remove_none' function and print the result
print("\nRemove None value from the said list:")
print(remove_none(nums)) 

Sample Output:

Original list:
[12, 0, None, 23, None, -55, 234, 89, None, 0, 6, -12]

Remove None value from the said list:
[12, 0, 23, -55, 234, 89, 0, 6, -12]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find the maximum and minimum values in a given list of tuples using lambda function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/lambda/python-lambda-exercise-52.php