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

Print values from one list not contained in another

I want to check whether the elements in two arrays are different using Python.

I don’t want to use numpy and sticking with general Python.

Here is an example below:

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

array1 = [1,2,3,4,5,6,7]
array2 = [1,2,3,4,5,6,7,8,9,10]

I expect the output to be [8,9,10]

So far I’ve tried to carry out a for loop

    arr1 = [1,2,3,4,5,6,7]
    arr2 = [1,2,3,4,5,6,7,8,9,10]
    for x in range(len(arr1)):
        for y in range(len(arr2)):
            if arr1[x] != arr2[y]:
                print(arr2[y])

But, I receive this as output from print statement – 2345678910134567891012456789101235678910123467891012345789101234568910

>Solution :

Without numpy, but with python one-liner:

res = [x for x in array2 if x not in array1]
print(res) # Output : [8, 9, 10]

Equivalent method for conventional iteration

lst = []
for x in array2:
    if x not in array1:
        lst.append(x)
print(lst) # Output : [8, 9, 10]
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