473,385 Members | 1,829 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

how to break a for loop?

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[i]
else:
break

but it removes ALL zeros from list. What's up?
P.S. I feel SO stupid asking this quastion... ;-)

Feb 20 '06 #1
12 1516
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[i]
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

Feb 20 '06 #2
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

Feb 20 '06 #3
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

Feb 20 '06 #4
-----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[i]
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+mVpdIssYB9vBoMRAl4hAJ9RnvgvEo5NsutG9KmD6q OEL7VyFgCfeLit
h7FLsbRvHR1z5DSxSPZHFlY=
=SY2U
-----END PGP SIGNATURE-----
Feb 21 '06 #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[i]
else:
break

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

--Scott David Daniels
sc***********@acm.org
Feb 21 '06 #6

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 '06 #7
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.

Feb 21 '06 #8
bo****@gmail.com 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
Feb 21 '06 #9

Giovanni Bajo wrote:
bo****@gmail.com 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 '06 #10
Thanks to everybody for help. Python community is very friendly and
helpfull indeed!

Feb 21 '06 #11
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 '06 #12

bearophileH...@lycos.com 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 '06 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Sandman | last post by:
Ok, so I have PHP set upp to ato_prepend and auto_append files to every script I run. So if I someone surfs to /index.php, these scripts run: init.php -> set up DB connections and...
5
by: Glen Wheeler | last post by:
Hello All. I've been coding in python for a reasonable amount of time now (coding in total for approx. 20 years) and am writing a performance intensive program in python. The problem I'm having...
10
by: Scott Brady Drummonds | last post by:
Hi, everyone, I have a bug in a script of several hundred lines of code that I cannot figure out. I have attempted (unsuccessfully) to duplicate this problem in a smaller script that I can post...
5
by: Ann | last post by:
I have trouble sometimes figuring out where break and continue go to. Is there some easy way to figure it out, or a tool? TIA Ann
5
by: viza | last post by:
Hi! Suppose I have int i,j,k; for(i=0;i<I;++i){ /* loop 1 */ for(j=0;j<J;++j){ /* loop 2 */ for(k=0;k<K;++k){ /* loop 3 */ if(test){
3
by: deko | last post by:
I have a logging routine that's supposed to silently log errors caught by error handler code on certain functions. The problem is sometimes stuff happens and the error handler can get caught in a...
25
by: chunhui_true | last post by:
In <<expert c>>I know the break in if wich is scoped in switch is break the switch,like: switch c case 1: if(b){ break; } ...... But like this: while(a){
5
by: tony collier | last post by:
To break out of a loop i have seen some people use RETURN instead of BREAK I have only seen RETURN used in functions. Does anyone know why RETURN is used instead of BREAK to kill loops?
3
by: Krish | last post by:
Hello, This is an issue that I have encountered several times but have just used a workaround to solve. What is the accepted practice for breaking out of nested loops? For example: while(...
26
by: a.mil | last post by:
I am programming for code-speed, not for ansi or other nice-guy stuff and I encountered the following problem: When I have a for loop like this: b=b0; for (a=0,i=0;i<100;i++,b--) { if (b%i)...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.