Ad

Most Time/space Efficient Way To Check If All Elements In List Of Integers Are 0

- 1 answer

This is an implementation question for Python 2.7

Say I have a list of integers called nums, and I need to check if all values in nums are equal to zero. nums contains many elements (i.e. more than 10000), with many repeating values.

Using all():

if all(n == 0 for n in set(nums)):  # I assume this conversion from list to set helps?
    # do something

Using set subtraction:

if set(nums) - {0} == set([]):
    # do something

Edit: better way to do the above approach, courtesy of user U9-Forward

if set(nums) == {0}:
    # do something

How do the time and space complexities compare for each of these approaches? Is there a more efficient way to check this?

Note: for this case, I am trying to avoid using numpy/pandas.

Ad

Answer

Any set conversion of nums won't help as it will iterate the entire list:

if all(n == 0 for n in nums):
    # ...

is just fine as it stops at the first non-zero element, disregarding the remainder.

Asymptotically, all these approaches are linear with random data. Implementational details (no repeated function calls on the generator) makes not any(nums) even faster, but that relies on the absence of any other falsy elements but0, e.g. '' or None.

Ad
source: stackoverflow.com
Ad