3

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.

3
  • 4
    That's not a python list, FYI. Commented Dec 2, 2013 at 12:42
  • Why don't you slice the list before you count? Something like count(Lux[14:16]). Commented Dec 2, 2013 at 12:43
  • Evert, I want somthing like this: valueInLux = Lux[i] #Lux[i] = 0 LuxNumberOfRows = Lux.count(valueInLux) Where Lux is the list, but for this I want only to run from 14 to 16. Commented Dec 2, 2013 at 12:45

1 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

1 Comment

list.count and slicing was exactly what I need! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.