Test If Tuple Contains Only None Values With Python
I need to find if my tuple contains only None value. I use this code but i not sure it's the good practice: # coding=utf8 def isOnlyNoneValuesTuple(t): ''' test if tuple c
Solution 1:
returnall(item isNonefor item in t)
Solution 2:
returnset(t) == {None}
Although I guess I'd use all() in practice.
Solution 3:
return t.count(None) == len(t)
and it is faster than using all
:
>>>setup = 't = [None, None]*100; t[1] = 1'>>>timeit.timeit('all(item is None for item in t)', setup=setup)
0.8577961921691895
>>>timeit.timeit('t.count(None) == len(t)', setup=setup)
0.6855478286743164
and speed of all
decreases according to index of not None
element:
>>>setup = 't = [None, None]*100; t[100] = 1'>>>timeit.timeit('all(item is None for item in t)', setup=setup)
8.18800687789917
>>>timeit.timeit('t.count(None) == len(t)', setup=setup)
0.698199987411499
BUT with big lists all is faster:
>>>setup = 't = [None, None]*10000; t[100] = 1'>>>timeit.timeit('t.count(None) == len(t)', setup=setup)
47.24849891662598
>>>timeit.timeit('all(item is None for item in t)', setup=setup)
8.114514112472534
BUT not always though:
>>>setup = 't = [None, None]*10000; t[1000]=1'>>>timeit.timeit('t.count(None) == len(t)', setup=setup)
47.475088119506836
>>>timeit.timeit('all(item is None for item in t)', setup=setup)
72.77452898025513
Conclusion that i make for myself about speed of all or count - very depends of data. If probability that you have all None in very big list - dont use all, it is very slow in that case.
Solution 4:
I second BrenBarn's answer, it's very Pythonic. But since you also asked about testing the code, I'll add my two cents.
You can create appropriate data structures by making use of the fact that Python allows you to multiply a list containing a single element by a factor n
to get a list that contains the same element n
times:
print(isOnlyNoneValuesTuple(tuple(10 * [None])))
print(isOnlyNoneValuesTuple(tuple(3 * [None] + ["val"] + 4 * [None])))
Post a Comment for "Test If Tuple Contains Only None Values With Python"