Search code examples
pythonlistalgorithm

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:

arr1 = [1,2,3,4,5,6,7]
arr2 = [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

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

  • 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]