Python assert all elements in list is not none

Viewed 3428

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!!

3 Answers

Unless you have a weird element that claims it equals None:

assert None not in [a, b, c]

Do you mean by all:

>>> assert all(i is not None for i in ['a', 'b', 'c'])
>>>

Or just simply:

assert None not in ['a', 'b', 'c']

P.S just noticed that @don'ttalkjustcode added the above.

Or with min:

>>> assert min(a, key=lambda x: x is not None, default=False)
>>>

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.

Related