how to break a for loop?

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

1. Gregory PetrosyanGuest

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

2. Petr JakesGuest

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

3. Jesus Rivero - (Neurogeek)Guest

-----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
4. Scott David DanielsGuest

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
5. =?ISO-8859-1?Q?Sch=FCle_Daniel?=Guest

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[:]):

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

uda4i

hth, Daniel

=?ISO-8859-1?Q?Sch=FCle_Daniel?=, Feb 21, 2006
6. =?ISO-8859-1?Q?Sch=FCle_Daniel?=Guest

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
7. 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
8. Dennis Lee BieberGuest

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 <
> ============================================================== <
> Overflow Page: <http://wlfraed.home.netcom.com/> <

Dennis Lee Bieber, Feb 21, 2006
9. Steven D'ApranoGuest

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
10. Giovanni BajoGuest

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
11. 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
12. Gregory PetrosyanGuest

Thanks to everybody for help. Python community is very friendly and

Gregory Petrosyan, Feb 21, 2006
13. Guest

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

import itertools as it
from operator import __not__

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:]

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:

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

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

l = [0] * n + [1] * n
t = clock()
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
14. 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