Home > Mobile >  how to check items of one list in another in python with loops
how to check items of one list in another in python with loops

Time:10-11

I want to check for a certain condition list and then print it suppose i want to check items of a in b

I want to check for values of list "a" in list "b" so i used this code

   a=[1,2]
   b=[1,2,3,4,5,6,7,8,9,]
   c=[]
   for i in a:   
      for j in b:
           if i!=j:
           c.append(j)

but i am getting infinite loop when i run this code code please help me.

CodePudding user response:

It is unclear what behavior you would like to implement, but I guess you want to filter out elements in b that appear in a. If so, you can do this:

a = [1, 2]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
c = []
for i in b:
    if not i in a:
        c.append(i)
print(c)

The result:

[3, 4, 5, 6, 7, 8, 9]

CodePudding user response:

The infinite loop is probably because Line 7 is missing an indentation.

Furthermore, if you are trying to find the list of values of list a in b, it should be

i == j

instead of

i != j
  • Related