Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding elements of one list in another in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

J=[[1,4]]

>Solution :

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading