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)
Ivan
  • 11
  • 1

2 Answers2

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))
Nate
  • 12,499
  • 5
  • 45
  • 60
1
y = filter(lambda i: i != 0, y)
jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • note - filter+lambda is often said to be slower than a list comprehension; you might be interested in [this related answer by Alex Martelli](http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map). – Nate Aug 10 '11 at 19:15