0

This is a very simple question I guess but I just can't find how to make it work, I have 2 list, one is empty the other one has 2 elements, in order to continue: If an element from list1 IS NOT in list2 then REMOVE it from list1, for this scenario at the end list1 should be in empty, but it turns out that at the end it keeps 'orange'!

#Try 1:
for element in list1:
   if element not in list2:
      list1.remove(element)

 print(list1)
 >['orange']


#Try 2:
list1 = ['apple','orange']
list2 = []
print("len",len(list1)-1)

for i in range(0,len(list1)-1):
    if list1[i] not in list2:
        list1.remove(list1[i])
        
print(list1)
>['orange']

thanks in advance

Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
Berny
  • 113
  • 11
  • Does this answer your question? [Strange result when removing item from a list while iterating over it](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) – Shaido Jul 14 '21 at 01:51

1 Answers1

0

Try to iterate through a copy of list1 instead:

list1 = ['apple', 'orange']
list2 = []

for element in list1.copy():
   if element not in list2:
       list1.remove(element)


print(list1)
R. Marolahy
  • 1,325
  • 7
  • 17