Natan
Natan

Reputation: 71

How to break while loop at a certain index but then run until end of a list?

I have the code below, I wish to run the while loop to remove a specific value from the list but not remove it on a certain index and still loop through the whole list without removing that specific occurrence.

a = 20
i = [5, 15, 20, 25, 50, 20, 80, 90, 20]
while a in i:
   i.remove(a)
    if a == i.index(5):
       continue
  print(i)

Maybe it's not supposed to be done with while loop but since learning the break or continue functions, i thought to give it a try. Thanks!

Upvotes: 2

Views: 853

Answers (1)

Ronald
Ronald

Reputation: 3315

Typically something you can solve with a list comprehension:

[ el for i, el in enumerate(lst) if i == 3 or el != 25]

Creates a new list while looping over the original one and adds all the elements that are not 25 (the one you want to remove) but still adds it if i==3, the position that is protected.

Upvotes: 7

Related Questions