Remove elements from a list

Hi guys!
I’m new in python.

I just have a simple question:
I have two Lists of int (the lists have different number of elements).
I have to check if the elements of List2 exist in List1.
If the elements already exist, I want to remove them from List1.

I made this code:

list1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]

list2 = [9,17]

for i in range(len(list1)):
for j in range(len(list2)):
if list2[j] == list1[i]:

but I received an error massage:

IndexError: list index out of range
→ if list2[j] == list1[i]:

Could you please help me to solve this issue?

thank you!!!

If you remove elements while iterating over the indices, you will:

  • Run out of elements before running out of indices and
  • probably skip elements.

Some options to address this might be to pick one of:

  • Don’t modify the original list, instead create a new list just with elements that don’t exist in both lists
  • Create a copy of the list. Modify one copy while looping over the other
  • Loop from back to front. The deletions (if done by index instead of by value) won’t affect the unexamined elements.

Thank you!!!
But I would be very gratefull if you post a solution.
I’m trying to do what you suggest but it’s not so easy…

Thank you in advance

Here’s the simplest solution I can think of, which uses a list comprehension. This creates a new list and assigns it to the variable list1.

list1 = [x for x in list1 if x not in list2]

If you need to modify the original list instead of creating a new list, you can do

list1[:] = [x for x in list1 if x not in list2]

Thank you so much!