1

5 - Write a code that takes values from one list, based on the values from another list and print the text of the output

#base list: list1 = [1, 7, 5, 2, 10, 34, 621, 45, 7, 76, 23, "a", 14, 6]

#to exclude from base list list2 = ['a', 'b', 'c', 7, 10, 23, 14]

Right Answer: List1 lost 6 elements and now has 8 elements

My code :

lost=0
for i in list1:
    if i in list2:
        list1.remove(i)
       lost+=1
print("List1 lost  {} elements and now has  {} elements".format(lost,len(list1)))

I've been printed the List 1 after ran the code and that was the answer:

list1 = [1, 5, 2, 34, 621, 45, 76, 'a', 6]

Why the 'a' are nothing being excluded from list1 ?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

1 Answers1

1

You can use a list comprehension to iterate over list1 and keep elements that are not also in list2, for performance reasons you can reduce list2 to a set to keep only unique elements and make the membership check faster.

>>> list1 = [i for i in list1 if i not in set(list2)]
>>> list1
[1, 5, 2, 34, 621, 45, 76, 6]

Your current implementation will not work because you should not remove items from a list as you are iterating through it, see this post for further details about that.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218