how to break a for loop?

G

Gregory Petrosyan

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... ;-)
 
P

Petr Jakes

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
 
J

Jesus Rivero - (Neurogeek)

-----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 said:
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-----
 
S

Scott David Daniels

Gregory said:
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
(e-mail address removed)
 
?

=?ISO-8859-1?Q?Sch=FCle_Daniel?=

Gregory said:
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?=

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
 
B

bonono

Gregory said:
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)
 
D

Dennis Lee Bieber

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

--
 
S

Steven D'Aprano

Petr said:
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*
 
G

Giovanni Bajo

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.
 
B

bonono

Giovanni said:
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).
 
G

Gregory Petrosyan

Thanks to everybody for help. Python community is very friendly and
helpfull indeed!
 
B

bearophileHUGS

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
 
B

bonono

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".
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top