1

How can i remove elements with a value of 0 as they pop upp in this loop?

y = [4, 2, 7, 9] x = input("run?") while x: for i in range(len(y)): y[i] -= 1 y.append(len(y)) print(y) 
1
  • 3
    while x will put you into an infinite loop if x evaluates to True Commented Aug 10, 2011 at 19:07

2 Answers 2

2

you could always use a list comprehension to filter them:

for i in range(len(y)): y[i] -= 1 y = [x for x in y if x != 0] # <-- added here y.append(len(y)) 

EDIT:

I'm silly - these operations could even be combined as so:

while whatever: #<-- fix as suggested by comment on your question y = [z-1 for z in y if z > 1] y.append(len(y)) 
Sign up to request clarification or add additional context in comments.

Comments

1
y = filter(lambda i: i != 0, y) 

1 Comment

note - filter+lambda is often said to be slower than a list comprehension; you might be interested in this related answer by Alex Martelli.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.