w3resource

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


52. Remove None Values Lambda

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]

For more Practice: Solve these Related Problems:

  • Write a Python program to remove all falsy values (None, 0, '', False) from a given list using lambda.
  • Write a Python program to filter out None and empty string values from a list using lambda.
  • Write a Python program to remove None values from a list and then sort the remaining elements using lambda.
  • Write a Python program to remove None values from a list and replace them with a specified default value using lambda.

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.



Follow us on Facebook and Twitter for latest update.