How to scan a big list to find if all elements match the ones of a second, smaller, list?

Viewed 80

I'm hvaing a hard time with a problem which I thought was pretty simple. I have two lists:

  1. A small one, that looks like this:
list1 = ['A', 'B', 'C', 'D','E']
  1. The second list is much bigger, going on for about 800 elements. It looks like this:
list2 = ['E', 'B', 'F', 'A', 'C', 'N'...]

I want to scan list2 and see if all of its elements are the same as the ones in list1. If they are different, I want to see which are the elements that differ and cancel them from list2. In this example, I want to print "F" and "N" from list2 and cancel them.

I tried:

found = False
lenght2 = len(list2)
i = 0
for j in list1:
  for i in range(0, lenght2):
     if i != j:
        found = True
        #I don't know how to cancel i
        print(i)
        i = i + 1
     break

However, the whole thing does not work. Is there anyone who could help me?

2 Answers

You could go through all of list2 then check if it is in list one, like this:

for i in range(len(list2)):
  if list2[i] in list1:
    pass
  else:
    #Cancel list2[i] ? Or whatever.

Keep it simple:

There's no need to use nested loops here -- you are removing elements from list2, based on information from list1, so loop through list2.

list1 = ['A', 'B', 'C', 'D', 'E']
list2 = ['E', 'B', 'F', 'A', 'C', 'N']

for e in list2[:]:
    if e not in list1:
        list2.remove(e)
print(list2)

This code loops through list2 and checks for each element (e) if it occurs in list1. If not, it removes it from list2.

Note: the use of list2[:] here rather than list2 is due to this.


Or use a list comprehension:

list1 = ['A', 'B', 'C', 'D', 'E']
list2 = ['E', 'B', 'F', 'A', 'C', 'N']

list2 = [e for e in list2 if e in list1]
print(list2)

See more about how list comprehensions work here.


In both cases, you should get:

['E', 'B', 'A', 'C']
Related