Question

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 contains only None values
    """
    if not len(tuple(itertools.ifilter(None, t))):
        return True
    else:
        return False

print isOnlyNoneValuesTuple((None,None,None,None,None,None,None,None,None,None,None,None,))
print isOnlyNoneValuesTuple((None,None,None,"val",None,None,None,None,))

Do you know other good practice to test it?

Thank you for your opinions

Was it helpful?

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.

OTHER TIPS

return all(item is None for item in t)
return set(t) == {None}

Although I guess I'd use all() in practice.

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])))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top