Velocity Reviews > lists with zero-valued elements

# lists with zero-valued elements

Nick Forest
Guest
Posts: n/a

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

Skip Montanaro
Guest
Posts: n/a

 12-27-2003

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

Alex Martelli
Guest
Posts: n/a

 12-27-2003
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
Guest
Posts: n/a

 12-27-2003
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