0

I am trying to remove elements from the list if the element is even ,the code runs partially it does not removes 12 from it .I have been stuck at this point does anyone have an idea what is the problem and what can be the optimized solution for it?

 lst=[0,3,5,8,12,2] #created a list 

 for i in lst:
     if(i%2==0):
         lst.remove(i)    #removes elements from the list 
  print(lst)


O/P:[3, 5, 12]
Karan Bari
  • 75
  • 3
  • 10
  • 3
    You are modifying the same list that you are looping through. Never a good idea. – b-fg Dec 06 '18 at 15:44
  • Instead of removing the elements that you do not want, build a new list of elements that you do want. – DYZ Dec 06 '18 at 15:44

2 Answers2

1

Modifying a list as you loop over it is a common pitfall.

The correct and safe way to do it, is to actually recreate the list with a list-comprehension or a filter.

  • List-comprehension version:

    lst = [x for x in lst if x%2!=0]
    
  • filter version:

    lst = list(filter(lambda x: x%2!=0, lst))
    

Both code snippets result in:

lst = [3, 5]
Ma0
  • 15,057
  • 4
  • 35
  • 65
0

Simply use python powerful list comprehension:

filtered_list =[i for i in old_list if i % 2 != 0]

trsvchn
  • 8,033
  • 3
  • 23
  • 30
  • 1
    It would be useful if you could explain a little about the code snippet. What is the name for the code you have used, so the OP can learn from it and maybe search better in the future. – Phil Dec 06 '18 at 16:07
  • Thanks for your advice, I am novice here, so that was helpful – trsvchn Dec 11 '18 at 13:13