Write a python program to remove none value from a given list using lambda function

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

Last update on December 22 2020 13:55:27 (UTC/GMT +8 hours)

Python: Remove None value from a given list

Last update on June 23 2021 06:16:30 (UTC/GMT +8 hours)

Python | Remove None values from list

Due to the upcoming of Machine Learning, the focus has now moved on handling the None values than ever before, the reason behind this is that it is the essential step of data preprocessing before it is fed into further techniques to perform. Hence, removal of None values in essential and knowledge of it is a must. Let’s discuss certain ways in which this is achieved.

Method #1 : Naive Method
In naive method, we iterate through the whole list and append all the filtered, non-None values into a new list, hence ready to be performed with subsequent operations.




# Python3 code to demonstrate
# removing None values in list
# using naive method
# initializing list
test_list = [1, None, 4, None, None, 5, 8, None]
# printing original list
print ("The original list is : " + str(test_list))
# using naive method
# to remove None values in list
res = []
for val in test_list:
if val != None :
res.append(val)
# printing result
print ("List after removal of None values : " + str(res))
Output: The original list is : [1, None, 4, None, None, 5, 8, None] List after removal of None values : [1, 4, 5, 8]


Method #2 : Using list comprehension
The longer task of using the naive method and increasing line of codes can be done in a compact way using this method. We just check for True values and construct the new filtered list.




# Python3 code to demonstrate
# removing None values in list
# using list comprehension
# initializing list
test_list = [1, None, 4, None, None, 5, 8, None]
# printing original list
print ("The original list is : " + str(test_list))
# using list comprehension
# to remove None values in list
res = [i for i in test_list if i]
# printing result
print ("List after removal of None values : " + str(res))
Output:

The original list is : [1, None, 4, None, None, 5, 8, None] List after removal of None values : [1, 4, 5, 8]


Method #3 : Using filter()
filter function is the most concise and readable way to perform this particular task. It checks for any None value in list and removes them and form a filtered list without the None values.




# Python3 code to demonstrate
# removing None values in list
# using filter()
# initializing list
test_list = [1, None, 4, None, None, 5, 8, None]
# printing original list
print ("The original list is : " + str(test_list))
# using filter()
# to remove None values in list
res = list(filter(None, test_list))
# printing result
print ("List after removal of None values : " + str(res))
Output: The original list is : [1, None, 4, None, None, 5, 8, None] List after removal of None values : [1, 4, 5, 8]

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




Article Tags :
Python
Python Programs
Python list-programs

Remove None values from a list in Python

October 18, 2020 ‐2min read

With Python you have multiple options to remove None values from a list. Those options include a basic for loop or by using list comprehension.

A more readable option, by personal opinion, is to use the filter function.

cocktails = ['Mojito', None, 'Pina Colada'] # Remove None values in list drinks = list(filter(None, cocktails)) print(drinks) # => ['Mojito', 'Pina Colada']

The filter function takes a function and iterable as parameters, giving it the following signature: filter(function, iterable). And the filter function returns a filter object, so depending on your use-case you might want to cast it to a list again with list().

All elements that in the iterable are passed to the function. If the function returns True for that specific element, that element is kept present. If it returns False, it is filtered out.

If you pass None as the function, the identity function is used instead. This causes all elements that are evaluated as False to be filtered out, so besides None empty strings, 0 and False are too. Which can cause unwanted behavior.

true_and_false = [True, False, None, False, False, True] true_and_false = list(filter(None, true_and_false)) print(true_and_false) # => [True, True]

Thus, in the first example passing None as a filter function does suffice. But in our cases you might need to be more explicit when you filter a list, to do you can use list comprehension or write your own callback function.

So the following example uses a lambda function to filter out None values, but it keeps the False's in there as well.

true_and_false = [True, False, None, False, False, True] # Filter out values with a lambda function true_and_false = list(filter(lambda x: x is not None, true_and_false)) print(true_and_false) # => [True, False, False, False, True]

And to include an example using list comprehension as well.

true_and_false = [True, False, None, False, False, True] # Filter out values with list comprehension true_and_false = [x for x in true_and_false if x is not None] print(true_and_false) # => [True, False, False, False, True]

Python filter()

In this tutorial, we will learn about the Python filter() function with the help of examples.

The filter() function extracts elements from an iterable (list, tuple etc.) for which a function returns True.

Example

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # returns True if number is even def check_even(number): if number % 2 == 0: return True return False
# Extract elements from the numbers list for which check_even() returns True even_numbers_iterator = filter(check_even, numbers)
# converting to list even_numbers = list(even_numbers_iterator) print(even_numbers) # Output: [2, 4, 6, 8, 10]

Background

Lists are an increasingly popular topic for those who are starting to learn Python as well as for those who are already experienced with the language. If we believe the search results in Google Trends, the search interest in this topic has been rising each and every year.

If you are a regular visitor to forums to answer or ask questions about Python programming, such as Stack Overflow, Quora or Reddit, you might know the reason behind it.

A lot of Python questions find their ways to these forums and continue to persist there, where users mark some as ‘duplicate’ or ‘sticky’, upvote them or discuss the right solution with others.

With this blog post, DataCamp wants to help you to tackle one topic, namely, the most frequently asked questions about lists in Python, and this in an interactive way!

How to Use Python Lambda Functions

by Andre Burgaud best-practices intermediate python
Mark as Completed
Tweet Share Email

Table of Contents

Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: How to Use Python Lambda Functions

Python and other languages like Java, C#, and even C++ have had lambda functions added to their syntax, whereas languages like LISP or the ML family of languages, Haskell, OCaml, and F#, use lambdas as a core concept.

Python lambdas are little, anonymous functions, subject to a more restrictive but more concise syntax than regular Python functions.

By the end of this article, you’ll know:

  • How Python lambdas came to be
  • How lambdas compare with regular function objects
  • How to write lambda functions
  • Which functions in the Python standard library leverage lambdas
  • When to use or avoid Python lambda functions

Notes: You’ll see some code examples using lambda that seem to blatantly ignore Python style best practices. This is only intended to illustrate lambda calculus concepts or to highlight the capabilities of Python lambda.

Those questionable examples will be contrasted with better approaches or alternatives as you progress through the article.

This tutorial is mainly for intermediate to experienced Python programmers, but it is accessible to any curious minds with interest in programming and lambda calculus.

All the examples included in this tutorial have been tested with Python 3.7.

Take the Quiz: Test your knowledge with our interactive “Python Lambda Functions” quiz. Upon completion you will receive a score so you can track your learning progress over time:

Take the Quiz »

Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.