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
  • 56,466
  • 29
  • 168
  • 265
Marek Grzyb
  • 177
  • 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
  • 818
  • 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
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
  • 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
  • 17,045
  • 10
  • 39
  • 63
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,631
  • 4
  • 30
  • 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,850
  • 2
  • 15
  • 36
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
  • 145,886
  • 38
  • 333
  • 352
  • 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
  • 27,088
  • 20
  • 102
  • 114
0
f = sum([1 for x in MyVar if x!= 0])

One line :)

PYA
  • 8,096
  • 3
  • 21
  • 38
0

Using sum of iterator:

sum(x != 0 for x in MyVar)
Jonas Adler
  • 10,365
  • 5
  • 46
  • 73