Home > Mobile >  Finding missing element in a list in Python
Finding missing element in a list in Python

Time:12-28

I have two lists J2 and J10. I am trying to find the elements in J10 which are absent in J2 but I am getting an error. I present the expected output.

J2=[128, 4, 6, 7, 8, 9, 10]

J10=[4, 6, 7, 8, 9, 10, 13, 128]

J=[i for i in J10 not in J2]
print(J)

The error is

in <module>
    J=[i for i in J10 not in J2]

TypeError: 'bool' object is not iterable

The expected output is

[13]

CodePudding user response:

J=[i for i in J10 if i not in J2]

Or:

lst=[]
for i in J10:
    if i not in J2:
        lst.append(i)
#[13]

Or

set(J10)-(set(J2))

CodePudding user response:

J=[i for i in J10 if i not in J2]

CodePudding user response:

This will do the job:

temp = list(filter(lambda x: x not in J2, J10))
print(temp)

Here is why your code fails:

J10 not in J2 is treated as an expression that checks if J10 (as a whole is in J2). In other words, the J10 not in J2 will be either True or False and since a boolean is not a storage-like element such as a list, you can not iterate it. if you want to solve your problem with syntax you were trying, you should use:

J=[i for i in J10 if i not in J2]

CodePudding user response:

Try this way..

J2=[128, 4, 6, 7, 8, 9, 10]
J10=[4, 6, 7, 8, 9, 10, 13, 128]
J=list(set(J10).difference(J2))
print(J)

CodePudding user response:

print(set(J2).symmetric_difference(J10))

CodePudding user response:

Your code does not work because it's parsed as:

[i for i in (J10 not in J2)]

J10 not in J2 returns a boolean value that you can't iterate over. You are missing an if.

[i for i in J10 if i not in J2]

Sets may be useful here, though, as the membership check if O(len(J2)) and the outer loop is O(len(J10)), making this a potentially quite expensive approach.

>>> set(J10) ^ set(J2) & set(J10)
{13}

First we find the set of items that are unique to each set. TO ensure this contains only unique elements from J10, we then intersect with J10.

  • Related