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

Find different elements when comparing two Python lists

I have two lists. X list is bigger, Y list is smaller.
I want to find elements from Y list that are different from elements in X list, but also elements that are not part of the any element in X list. Also, elements from X list can not be part of elements in Y list.

For example A A is part of A A B, AA B is part of AA BB but A C A, C BB, S are not part of any element in Y.

Also, you will see that X has C A and Y has CC A, that is not allowed.

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

X = ["A A B", "A B C", "AA BB", "BB C A", "A C B", "BB C A", "X", "C A"]
Y = ["A A", "A C A", "AA B", "C BB", "S", "CC A"]

I have tried something like this, with different place of else but it does not work good

for x in X:
    for y in Y:
        if x in y or y in x:
            continue
    else:
        print(y)

Requested result:

C BB
S

>Solution :

  • Go over each element in Y.
  • For each one, go over each element in X.
  • If any of them contain each other in any direction – break.
  • Else, take the item:
X = ["A A B", "A B C", "AA BB", "BB C A", "A C B", "BB C A", "X", "C A"]
Y = ["A A", "A C A", "AA B", "C BB", "S", "CC A"]

for y in Y:
    for x in X:
        if y in x or x in y:
            break
    else:
        print(y)

Gives:

C BB
S

This uses the for/else construct which means that the else part will only be executed if the loop executed to exhaustion, without breaking.


Or, the shorter way by using any:

for y in Y:
    if not any(y in x or x in y for x in X):
        print(y)

or, by De Morgan’s laws we can use all:

for y in Y:
    if all(y not in x and x not in y for x in X):
        print(y)
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