# lists with zero-valued elements

Discussion in 'Python' started by Nick Forest, Dec 27, 2003.

1. ### Nick ForestGuest

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

Nick Forest, Dec 27, 2003

2. ### Skip MontanaroGuest

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

Skip Montanaro, Dec 27, 2003

3. ### Alex MartelliGuest

Nick Forest wrote:

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

'enumerate'...? As in, enumerate(n*[0]) ... ?

Alex

Alex Martelli, Dec 27, 2003
4. ### Alex MartelliGuest

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

Alex Martelli, Dec 27, 2003