shlomi
shlomi

Reputation: 549

Count number of values in python

I have a list look like this:

Lux = ([ 0 0 0 0 0 120 120 120 120 120 240 240 240 240 240 0 0 0 0 0 120 120 120 120 120])

I want to count how many zeros I have, but only from the 14 place, and let say until 16 place The answer will be in this case 2. I know that count function count all the appearance. How can I do it, but with out loop? I want this when I'm already in two loops, and don't want to add another one.

Thank you.

Upvotes: 3

Views: 784

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251146

Use list.count and slicing:

>>> lis = [0, 0, 0, 0, 0, 120, 120, 120, 120, 120, 240, 240, 240, 240, 240, 0, 0, 0, 0, 0, 120, 120, 120, 120, 120]
>>> lis[14:].count(0)
5
>>> lis[14:17].count(0)
2

Another option is to use sum and a generator expression, but this is going to be very slow compared to list.count:

>>> sum(1 for i in xrange(14, len(lis)) if lis[i]==0)
5
>>> sum(1 for i in xrange(14, 17) if lis[i]==0)
2

Timing comparisons:

In [4]: lis = [0, 0, 0, 0, 0, 120, 120, 120, 120, 120, 240, 240, 240, 240, 240, 0, 0, 0, 0, 0, 12
0, 120, 120, 120, 120]*10**5                                                                     

In [5]: %timeit lis[14:].count(0)                                                                
10 loops, best of 3: 64.7 ms per loop

In [6]: %timeit sum(1 for i in xrange(14, len(lis)) if lis[i]==0)                                
1 loops, best of 3: 307 ms per loop

Upvotes: 10

Related Questions