- Python assert all elements in list is not none [duplicate]
- 3 Answers 3
- Check if all elements in a list are None in Python
- Check if a list contains only None using for loop
- Frequently Asked:
- Generic function to check if all items in list matches a given item like None
- Check if a list contains only None using List comprehension
- Related posts:
Python assert all elements in list is not none [duplicate]
I was wondering if we could assert all elements in a list is not None , therefore while a = None will raise an error. The sample list is [a, b, c] I have tried assert [a, b, c] is not None , it will return True if any one of the elements is not None but not verifying all. Could you help figure it out? Thanks!!
assert [a, b, c] is not None will pass even if all the elements are None . The only thing that is None is. None . is means the same object, not an equality check. It also is not possible to create more instances of None ‘s type.
«assert [a, b, c] is not None, it will return True if any one of the elements is not None » no. that isn’t what is happening, it is doing an identity check for None . Any list is not None, in fact, any object except None is not None.
3 Answers 3
Unless you have a weird element that claims it equals None :
kudos, as this version also seems the fastest. If anyone curious, about 5x faster than all and checking if each element is not None , but very close in terms of performance to all([a, b, c])
@rv.kvetch all([a, b, c]) is significantly less safe, though, as any false value (e.g., a zero) will make that return False .
yep, I never said it was perfect; but somehow it performs much better than the one with the explicit None check, which seems slow by comparison.
>>> assert all(i is not None for i in ['a', 'b', 'c']) >>>
P.S just noticed that @don’ttalkjustcode added the above.
>>> assert min(a, key=lambda x: x is not None, default=False) >>>
default should be True , though I find min very weird for this. And for example it cries AssertionError for [0, 1, 2] even though there’s no None. Btw the correct faster all(. ) that I think you were trying earlier is as expected indeed faster, see @rv’s benchmark.
Midway in terms of performence between not in and all . Note that the sensible (go-to) version with all for this particular case will end up performing slow — but at least ahead of min
def assert_all_not_none(l): for x in l: if x is None: return False return True
Edit: here are some benchmarks for those intersted
from timeit import timeit def all_not_none(l): for b in l: if b is None: return False return True def with_min(l): min(l, key=lambda x: x is not None, default=False) def not_in(l): return None not in l def all1(l): return all(i is not None for i in l) def all2(l): return all(False for i in l if i is None) def all_truthy(l): return all(l) def any1(l): return any(True for x in l if x is None) l = ['a', 'b', 'c'] * 20_000 n = 1_000 # 0.63 print(timeit("all_not_none(l)", globals=globals(), number=n)) # 3.41 print(timeit("with_min(l)", globals=globals(), number=n)) # 1.66 print(timeit('all1(l)', globals=globals(), number=n)) # 0.63 print(timeit('all2(l)', globals=globals(), number=n)) # 0.63 print(timeit('any1(l)', globals=globals(), number=n)) # 0.26 print(timeit('all_truthy(l)', globals=globals(), number=n)) # 0.53 print(timeit('not_in(l)', globals=globals(), number=n))
Surprisingly the winner: all(list) . Therfore, if you are certain list will not contain falsy values like empty string or zeros, nothing wrong with going with that.
Check if all elements in a list are None in Python
In this article we will discuss different ways to check if a list contains only None or not.
sample_list = [None, None, None, None]
Now we want to confirm that all items in this list are None. There are different ways to do that. Let’s discuss them one by one,
Check if a list contains only None using for loop
The first solution that comes to our mind is using for loop.
Logic is, Iterate over all the items of a list using for loop and for each item check if it is None or not. As soon as a non None item is found, break the loop because it means all items of list are not None. Whereas, if the loop ends and not even a single non None item is found, then it proves that all items of the list are None.
Frequently Asked:
Let’s create a function that accepts a list and check if all items are none or not using the above logic,
def check_if_all_none(list_of_elem): """ Check if all elements in list are None """ result = True for elem in list_of_elem: if elem is not None: return False return result
Use this function to check if all items in list are None,
sample_list = [None, None, None, None] # Check if list contains only None result = check_if_all_none(sample_list) if result: print('Yes List contains all None') else: print('Not all items in list are None')
Yes List contains all None
Generic function to check if all items in list matches a given item like None
In the above example, we created a separate function just to check if all items in a list are None or not, although it does the work but it is not a reusable function. So, let’s create a generic function to check if all items of a list are same and also matches the given element,
def check_if_all_same(list_of_elem, item): """ Check if all elements in list are same and matches the given item""" result = True for elem in list_of_elem: if elem != item: return False return result
This function accepts a list and an item as an argument. Then checks if all items in the given list matches the given item using the same logic as previous example. We can use this function to check if all items of list are None,
sample_list = [None, None, None, None] # Check if all items in list are same and are None result = check_if_all_same(sample_list, None) if result: print('Yes List contains all None') else: print('Not all items in list are None')
Yes List contains all None
Now we can use this function at other places too like, to confirm if all elements in a list matches the given number or string etc.
Check if a list contains only None using List comprehension
Let’s look at a pythonic way to confirm if all items in a list are None,
def check_if_all_same_2(list_of_elem, item): """ Using List comprehension, check if all elements in list are same and matches the given item""" return all([elem == item for elem in list_of_elem])
Let’s use this function to check all items of list are None,
sample_list = [None, None, None, None] # Check if all items in list are same and are None result = check_if_all_same_2(sample_list, None) if result: print('Yes List contains all None') else: print('Not all items in list are None')
Yes List contains all None
It is a one line solution.
Using list comprehension we created a Boolean list from the existing list. Each element in this bool list corresponds to an item for the main list. Basically, in the List Comprehension we iterated over the given list and for each element we checked if it is None or not. If it is None then added True in the bool list else added False. Now using all() checked if the bool list contains only True or not. If all() function returns True, then it means our main list contains only None.
We can use this function in a generic way too. For example check if all items in the list matches a given string,
sample_list = ['is', 'is', 'is', 'is', 'is'] # Check if all items in list are string 'is' result = check_if_all_same_2(sample_list, 'is') if result: print('Yes List contains same elements') else: print('Not all items in list are same')
Yes List contains same elements
The complete example is as follows,
def check_if_all_none(list_of_elem): """ Check if all elements in list are None """ result = True for elem in list_of_elem: if elem is not None: return False return result def check_if_all_same(list_of_elem, item): """ Check if all elements in list are same and matches the given item""" result = True for elem in list_of_elem: if elem != item: return False return result def check_if_all_same_2(list_of_elem, item): """ Using List comprehension, check if all elements in list are same and matches the given item""" return all([elem == item for elem in list_of_elem]) def main(): print('*** Check if a list contains only None using for loop ***') sample_list = [None, None, None, None] # Check if list contains only None result = check_if_all_none(sample_list) if result: print('Yes List contains all None') else: print('Not all items in list are None') print('*** Check if a list contains only None using Generic function ***') sample_list = [None, None, None, None] # Check if all items in list are same and are None result = check_if_all_same(sample_list, None) if result: print('Yes List contains all None') else: print('Not all items in list are None') print('*** Check if a list contains only None using List comprehension ***') sample_list = [None, None, None, None] # Check if all items in list are same and are None result = check_if_all_same_2(sample_list, None) if result: print('Yes List contains all None') else: print('Not all items in list are None') print('*** check if all items in the list matches a given string ***') sample_list = ['is', 'is', 'is', 'is', 'is'] # Check if all items in list are string 'is' result = check_if_all_same_2(sample_list, 'is') if result: print('Yes List contains same elements') else: print('Not all items in list are same') if __name__ == '__main__': main()
*** Check if a list contains only None using for loop *** Yes List contains all None *** Check if a list contains only None using Generic function *** Yes List contains all None *** Check if a list contains only None using List comprehension *** Yes List contains all None *** check if all items in the list matches a given string *** Yes List contains same elements