Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python- Find unmatched values from multiple lists [closed]

I'm new to python and I would like to get your advice regarding my function. What I want to do is below.

I have 2 lists A and B.(for example A = [1,2,3,4,5], B = [4,3,2,1]) I want to create a function which finds values in A which does not exist in list B. So in this case 5.

I wrote a function below but it does not work and I could not figure out what is wrong in the code.... Could anyone help me to understand what is the bug?? It seems easy but it is difficult for me. Thank you for your help!!

def finder(arr1,arr2):
    arr1 = sorted(arr1)
    arr2 = sorted(arr2)

    eliminated = []

    for x in arr1:
        if x not in arr2:
            eliminated = eliminated.append(x)
        else:
            pass
    return eliminated
like image 481
yusuke0426 Avatar asked Mar 05 '26 05:03

yusuke0426


2 Answers

The .append() method will modify the original list. Change the following line

eliminated = eliminated.append(x)

to

eliminated.append(x)

You also don't need to sort your lists.

like image 158
Selcuk Avatar answered Mar 06 '26 19:03

Selcuk


Here are three different ways to do it. The first way uses set difference, the second uses the builtin filter feature, and the third uses a list comprehension.

Python 2.7.12 (default, Jul  9 2016, 12:50:33)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> A=[1,2,3,4,5]
>>> B=[4,3,2,1]
>>> def a(x,y):
...   return list(set(x)-set(y))
...
>>> a(A,B)
[5]
>>> def b(x,y):
...   return filter(lambda A: A not in y, x)
...
>>> b(A,B)
[5]
>>> def c(x,y):
...   return [_ for _ in x if _ not in y]
...
>>> c(A,B)
[5]
like image 28
Charles D Pantoga Avatar answered Mar 06 '26 17:03

Charles D Pantoga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!