how to break a for loop?

Discussion in 'Python' started by Gregory Petrosyan, Feb 20, 2006.

  1. Hello!
    It's 1:56 o'clock in St.-Petersburg now, and I am still coding... maybe
    that's why I encountered stupid problem: I need to remove zeros from
    the begining of list, but I can't :-(. I use

    for i,coef in enumerate(coefs):
    if coef == 0:
    del coefs
    else:
    break

    but it removes ALL zeros from list. What's up?


    P.S. I feel SO stupid asking this quastion... ;-)
    Gregory Petrosyan, Feb 20, 2006
    #1
    1. Advertising

  2. Gregory Petrosyan

    Petr Jakes Guest

    zero_list=[0,0,0,0,0,1,2,3,4]
    for x in range(len(zero_list)):
    if zero_list[x]!=0: break
    nonzero_list=zero_list[x:]
    print nonzero_list

    but some more "pythonic" solutions will be posted from other users I
    guess :)

    HTH
    Petr Jakes
    Petr Jakes, Feb 20, 2006
    #2
    1. Advertising

  3. -----BEGIN PGP SIGNED MESSAGE-----
    Hash: SHA1

    Hello Gregory!

    I would also use lists to implement this. They are more practical and
    you could take advantage of pop() or remove() methods instead of using
    the Oh-so-Scary del. You could also use a lambda+map or reduce methods
    to remove all zeros or just do something like this:

    list_ = [0,0,0,1,0,0,1]
    print [ elm for elm in list_ if elm != 0 ]
    [1,1]



    Regards,

    Jesus (Neurogeek)

    Gregory Petrosyan wrote:
    > Hello!
    > It's 1:56 o'clock in St.-Petersburg now, and I am still coding... maybe
    > that's why I encountered stupid problem: I need to remove zeros from
    > the begining of list, but I can't :-(. I use
    >
    > for i,coef in enumerate(coefs):
    > if coef == 0:
    > del coefs
    > else:
    > break
    >
    > but it removes ALL zeros from list. What's up?
    >
    >
    > P.S. I feel SO stupid asking this quastion... ;-)
    >


    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.1 (GNU/Linux)
    Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

    iD8DBQFD+mVpdIssYB9vBoMRAl4hAJ9RnvgvEo5NsutG9KmD6qOEL7VyFgCfeLit
    h7FLsbRvHR1z5DSxSPZHFlY=
    =SY2U
    -----END PGP SIGNATURE-----
    Jesus Rivero - (Neurogeek), Feb 21, 2006
    #3
  4. Gregory Petrosyan wrote:
    > Hello!
    > It's 1:56 o'clock in St.-Petersburg now, and I am still coding... maybe
    > that's why I encountered stupid problem: I need to remove zeros from
    > the begining of list, but I can't :-(. I use
    >
    > for i,coef in enumerate(coefs):
    > if coef == 0:
    > del coefs
    > else:
    > break

    for index, coef in enumerate(coefs):
    if coef:
    if index:
    del coefs[: index]
    break

    --Scott David Daniels
    Scott David Daniels, Feb 21, 2006
    #4
  5. Gregory Petrosyan wrote:
    > Hello!
    > It's 1:56 o'clock in St.-Petersburg now, and I am still coding... maybe
    > that's why I encountered stupid problem: I need to remove zeros from
    > the begining of list, but I can't :-(. I use
    >
    > for i,coef in enumerate(coefs):
    > if coef == 0:
    > del coefs
    > else:
    > break
    >
    > but it removes ALL zeros from list. What's up?


    I don't know how enumerate is implemented, but I would
    suspect that modifying the list object in the loop
    through del is asking for trouble

    try
    for i,coef in enumerate(coefs[:]):
    instead

    > P.S. I feel SO stupid asking this quastion... ;-)


    uda4i

    hth, Daniel
    =?ISO-8859-1?Q?Sch=FCle_Daniel?=, Feb 21, 2006
    #5
  6. I just spend some more seconds thinking about it :)

    lst = [0,0,0,1,2,3,0,11]

    try:
    del lst[0:lst.index(0)]
    except ValueError:
    pass

    is better solution
    =?ISO-8859-1?Q?Sch=FCle_Daniel?=, Feb 21, 2006
    #6
  7. Gregory Petrosyan

    Guest

    Gregory Petrosyan wrote:
    >I need to remove zeros from
    > the begining of list, but I can't :-(.


    I believe the following is almost a direct translation of the above
    sentence.

    import itertools as it
    a=[0,0,0,1,0]
    a[:]=it.dropwhile(lambda x: x is 0, a)
    , Feb 21, 2006
    #7
  8. On 20 Feb 2006 15:00:51 -0800, "Gregory Petrosyan"
    <> declaimed the following in
    comp.lang.python:

    > Hello!
    > It's 1:56 o'clock in St.-Petersburg now, and I am still coding... maybe
    > that's why I encountered stupid problem: I need to remove zeros from
    > the begining of list, but I can't :-(. I use
    >

    Only from the beginning? (I think some of the other responses, which
    I'd glanced over using Google-Groups at work, were stripping ALL zero
    elements)...

    May not be the most efficient, but it is definitely clear:

    while len(coefs) > 1 and coefs[0] == 0:
    coefs = coefs[1:]

    --
    > ============================================================== <
    > | Wulfraed Dennis Lee Bieber KD6MOG <
    > | Bestiaria Support Staff <
    > ============================================================== <
    > Home Page: <http://www.dm.net/~wulfraed/> <
    > Overflow Page: <http://wlfraed.home.netcom.com/> <
    Dennis Lee Bieber, Feb 21, 2006
    #8
  9. Petr Jakes wrote:

    > zero_list=[0,0,0,0,0,1,2,3,4]
    > for x in range(len(zero_list)):
    > if zero_list[x]!=0: break
    > nonzero_list=zero_list[x:]
    > print nonzero_list
    >
    > but some more "pythonic" solutions will be posted from other users I
    > guess :)



    That looks perfectly Pythonic to me.

    You know, just because Python has for loops and
    multi-line blocks of code doesn't mean we shouldn't use
    them *wink*


    --
    Steven.
    Steven D'Aprano, Feb 21, 2006
    #9
  10. wrote:

    >> I need to remove zeros from
    >> the begining of list, but I can't :-(.

    >
    > I believe the following is almost a direct translation of the above
    > sentence.
    >
    > import itertools as it
    > a=[0,0,0,1,0]
    > a[:]=it.dropwhile(lambda x: x is 0, a)



    Usa lambda x: x==0 or simply lambda x: x

    Using 'is' relies on the interpreter reusing existing instances of the
    immutable object '0', which is an implementation detail.
    --
    Giovanni Bajo
    Giovanni Bajo, Feb 21, 2006
    #10
  11. Gregory Petrosyan

    Guest

    Giovanni Bajo wrote:
    > wrote:
    >
    > >> I need to remove zeros from
    > >> the begining of list, but I can't :-(.

    > >
    > > I believe the following is almost a direct translation of the above
    > > sentence.
    > >
    > > import itertools as it
    > > a=[0,0,0,1,0]
    > > a[:]=it.dropwhile(lambda x: x is 0, a)

    >
    >
    > Usa lambda x: x==0 or simply lambda x: x
    >
    > Using 'is' relies on the interpreter reusing existing instances of the
    > immutable object '0', which is an implementation detail.


    stand corrected. But I don't think "lambda x: x" is I want as 0 would
    be false which would stop the dropwhile right away.

    For this particular case one can even use operator.not_ directly, which
    skip the lambda(has some peformance advantage).
    , Feb 21, 2006
    #11
  12. Thanks to everybody for help. Python community is very friendly and
    helpfull indeed!
    Gregory Petrosyan, Feb 21, 2006
    #12
  13. Gregory Petrosyan

    Guest

    This time it seems that using itertools gives slower results, this is
    the test code:

    import itertools as it
    from operator import __not__

    def trim_leading_zeros(seq):
    if not seq:
    return seq
    for pos, el in enumerate(seq):
    if el != 0:
    break
    if seq[pos] == 0:
    del seq[:]
    return seq
    return seq[pos:]

    def trim_leading_zeros2(seq):
    seq[:] = it.dropwhile(__not__, seq)
    return seq

    data = ([0,0,0,0,0,1,2,3,4],
    [1,2,3,4],
    [0,1],
    [0,0,0],
    [0,0,0,1],
    [])

    for l in data:
    print l, trim_leading_zeros(l), trim_leading_zeros2(l)

    from time import clock
    n = 3 * 10**5

    l = [0] * n + [1] * n
    t = clock()
    trim_leading_zeros(l)
    print round(clock()-t, 2), "s"

    l = [0] * n + [1] * n
    t = clock()
    trim_leading_zeros2(l)
    print round(clock()-t, 2), "s"

    Gives this output on my PC:

    [0, 0, 0, 0, 0, 1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]
    [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]
    [0, 1] [1] [1]
    [0, 0, 0] [] []
    [0, 0, 0, 1] [1] [1]
    [] [] []
    0.3 s
    2.86 s

    Bye,
    bearophile
    , Feb 21, 2006
    #13
  14. Gregory Petrosyan

    Guest

    wrote:
    > This time it seems that using itertools gives slower results, this is
    > the test code:

    Understandable, as dropwhile still needs to go through the whole list
    and the difference will be larger when the list get longer. Though I
    still prefer that if the list is not horribly long as it is like a
    spec. But then, one can always name the fast in place del slice version
    like "dropwhileFast".
    , Feb 21, 2006
    #14
    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. Replies:
    16
    Views:
    3,592
    steve
    Jul 11, 2006
  2. BartlebyScrivener

    keyboard command to break out of infinite loop?

    BartlebyScrivener, Apr 16, 2006, in forum: Python
    Replies:
    5
    Views:
    864
    BartlebyScrivener
    Apr 16, 2006
  3. Alex Pavluck
    Replies:
    5
    Views:
    274
    Petr Jakes
    Jun 27, 2006
  4. Replies:
    12
    Views:
    960
  5. Isaac Won
    Replies:
    9
    Views:
    372
    Ulrich Eckhardt
    Mar 4, 2013
Loading...

Share This Page