Finding elements of one list in another in Python

Question:

I have two lists J1,J2. I want to find elements of J1 which are not in J2. But I am getting an error. I present the expected output.

import numpy as np
J1=[[1, 2, 4, 6, 7, 9, 10]]
J2=[[0, 2, 0, 6, 7, 9, 10]]

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

The error is

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

TypeError: 'bool' object is not iterable

The expected output is

J=[[1,4]]
Asked By: bekarhunmain

||

Answers:

Taking J1 and J2 as list of lists for better understanding.

Code:

import numpy as np

J1 = [[1, 2, 4, 6, 7, 9, 10], [0, 2, 3, 1]]
J2 = [[0, 2, 0, 6, 7, 9, 10], [1, 3, 5]]

J = [[x for x in J1[i] if x not in J2[i]] for i in range(len(J1))]

print(J)

Output:

[[1, 4], [0, 2]]
Answered By: Yash Mehta
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.