Finding missing element in a list in Python

Question:

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]
Asked By: AEinstein

||

Answers:

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))
Answered By: God Is One

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]
Answered By: Mehdi Hamzezadeh
print(set(J2).symmetric_difference(J10))
Answered By: Mahipal Singh

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.

Answered By: Chris

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)
Answered By: Ananth R Shenoy
J=[i for i in J10 if i not in J2]
Answered By: Adithyan A
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.