标签云

微信群

扫码加入我们

WeChat QR Code

I have written a simple python program l=[1,2,3,0,0,1]for i in range(0,len(l)): if l[i]==0: l.pop(i)This gives me error 'list index out of range' on line if l[i]==0:After debugging I could figure out that i is getting incremented and list is getting reduced.However, I have loop termination condition i < len(l). Then why I am getting such error?


"I have loop termination condition i < len(l)"Why do you say that?Where in your code do you see that?

2019年07月24日35分50秒

S. Lott , i in range(0,len()) means 'i will go upto len(l)-1'

2019年07月23日35分50秒

Another python tip - you could have just written range(len(l)), as 0 is the default starting value.

2019年07月24日35分50秒

From PEP 8: Never use the characters l (lowercase letter el), O (uppercase letter oh), or I (uppercase letter eye) as single character variable names. python.org/dev/peps/pep-0008

2019年07月23日35分50秒

atv: What makes you think range(0,len(l)) has a result that varies when l is changed?Why do you think that?Where did you read it?

2019年07月23日35分50秒

You don't even need the lambda, since 0 evaluates to False.filter(None, l)

2019年07月23日35分50秒

In fact his lambda condition is wrong. But +1 for filter.

2019年07月24日35分50秒

Steve Losh - This is what I love about SO... Learning simple little tricks like that to save me keystrokes in the longrun! Thanks!

2019年07月24日35分50秒

-1: Why do you point a beginner to this legacy way? List comprehensions are now the preferred way to do this.

2019年07月23日35分50秒

-1 for filter or map.You should always use a list comprehension if it will do the job.

2019年07月24日35分50秒