3

I have list or/and tuple:

MyVar = [0,0,0,0,1,0,0,0,0]

And I want to count elements in this which are different from 0.

How to do that?

Ali
  • 54,239
  • 29
  • 159
  • 255
Marek Grzyb
  • 167
  • 13
  • Similar question: https://stackoverflow.com/questions/15375093/python-get-number-of-items-from-listsequence-with-certain-condition – user2314737 Aug 17 '17 at 20:49

10 Answers10

9

No need to generate lists, just:

len(MyVar) - MyVar.count(0)
Grisha S
  • 788
  • 1
  • 6
  • 15
3

Get the length of the sublist of all elements that are not 0

MyVar = [0,0,0,0,1,0,0,0,0]
len([x for x in MyVar if x != 0])
>> 1
AK47
  • 8,646
  • 6
  • 37
  • 61
  • 3
    Probably not a good idea to use `is` or `is not` to compare values. It's just an implementation detail that `0` is a constant and it's only a constant in CPython. `!=` would be better. – MSeifert Aug 17 '17 at 20:24
2

You could try:

>>> len(filter(lambda x: x != 0, MyVar))
1
o-90
  • 15,749
  • 10
  • 40
  • 61
2

The following should work:

>>> MyVar = [0,0,0,0,1,0,0,0,0]
>>> sum(map(bool, MyVar))
1

It will convert the list to a list of booleans, with value True iff an element is nonzero. Then it'll sum all elements by implicitly considering True having value 1 and False having value 0.

JuniorCompressor
  • 19,143
  • 4
  • 28
  • 57
1

Try with filter():

>>> my_var = [0, 0, 0, 0, 1, 0, 0, 0, 0]
>>> result = filter(lambda x: x > 0, my_var)
[1]
>>> print(len(result))
1
wencakisa
  • 5,360
  • 2
  • 14
  • 34
1

You could do a sum over a conditional generator expression which doesn't require any intermediate lists or unnecessary arithmetic operations:

>>> sum(1 for element in MyVar if element != 0)
1

or as pointed out by @Jean-François Fabre:

>>> sum(1 for element in MyVar if element)
1

In case the MyVar only contains numbers this counts the number of not-zero values.

MSeifert
  • 133,177
  • 32
  • 312
  • 322
  • 1
    or `sum(1 for element in MyVar if element)` – Jean-François Fabre Aug 17 '17 at 20:29
  • 1
    There is a subtle difference between "not zero" and "is truthy" - and the question asked for "not zero". In this case both would give the same result but they wouldn't if the list contains some weird values like empty strings/tuples/dicts/lists. – MSeifert Aug 17 '17 at 20:32
0

Not nearly as efficient as any of the answers above, but simple and straight forward nonetheless

myVar = [0,0,0,0,1,0,0,0,0]
count = 0

for var in myVar:
    if var != 0:
        count += 1
edm2282
  • 156
  • 6
0

With reduce from functools:

from functools import reduce

reduce((lambda x, y: x + (y>0)), MyVar, 0)
user2314737
  • 24,359
  • 17
  • 91
  • 104
0
f = sum([1 for x in MyVar if x!= 0])

One line :)

PYA
  • 7,018
  • 3
  • 18
  • 38
0

Using sum of iterator:

sum(x != 0 for x in MyVar)
Jonas Adler
  • 9,571
  • 3
  • 41
  • 73