lists with zero-valued elements

S

Skip Montanaro

Nick> Any body knows a trivial way to enumerate a list with n
Nick> zero-valued elements?

I'm not sure what you're asking. I'd enumerate a list with n zero-valued
elements the same way I'd enumerate one with m zero-valued elements:

nelements = len(somelist)

If I wanted to count how many elements were zero, I might do something like:

nzeros = 0
for element in somelist:
if element == 0:
nzeros += 1

or more succinctly:

nzeros = len([element for element in somelist if element == 0])

Skip
 
A

Alex Martelli

Skip Montanaro wrote:
...
If I wanted to count how many elements were zero, I might do something
like:

nzeros = 0
for element in somelist:
if element == 0:
nzeros += 1

or more succinctly:

nzeros = len([element for element in somelist if element == 0])

I'd do somelist.count(0) -- faster, more direct, and even more succint.


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top