lists with zero-valued elements

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

  1. Nick Forest

    Nick Forest Guest

    Any body knows a trivial way to enumerate a list with n zero-valued elements?
     
    Nick Forest, Dec 27, 2003
    #1
    1. Advertising

  2. 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
    #2
    1. Advertising

  3. 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
    #3
  4. 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
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Guest
    Replies:
    1
    Views:
    680
    Sajan
    Feb 4, 2004
  2. Zhiqiang Ye
    Replies:
    53
    Views:
    10,412
    Dan Pop
    Jun 28, 2004
  3. Gerard Flanagan
    Replies:
    3
    Views:
    494
    Terry Hancock
    Nov 19, 2005
  4. =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==

    List of lists of lists of lists...

    =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==, May 8, 2006, in forum: Python
    Replies:
    5
    Views:
    441
    =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==
    May 15, 2006
  5. Christopher Benson-Manica

    Doubles and zero/negative zero

    Christopher Benson-Manica, Jun 30, 2004, in forum: C Programming
    Replies:
    4
    Views:
    712
    Walter
    Jul 1, 2004
Loading...

Share This Page