Athena
Athena

Reputation: 37

Comparing two lists and removing matching values

I have a function that compares two lists with the purpose of removing the values that are the same and in the same position in both lists.

def remove(l1, l2):
    r = []
    for char in range(len(l1)):
        if l1[char] != l2[char]:
             r.append(char)
    return r

While this returns the index of the characters that are not the same, I'm unsure as to how to get it to return the characters from l1.

    remove(['S', 'T', 'U', 'V'], ['L', 'T', 'A', 'B'])
Expected:
    ['S', 'U', 'V']
Got:
    [0, 2, 3]

Thanks in advance!

Upvotes: 1

Views: 4533

Answers (4)

patruski
patruski

Reputation: 11

You could also do list comprehension with any magic. This works with lists of different sizes also.

We are checking l1 item "x" against all l2 items with Python's "in" keyword. The "any" returns True if any of items match, but we are reversing this with the "not" keyword.

def remove(l1, l2):
    return [x for x in l1 if not any([x in l2])]

remove(['S', 'T', 'U', 'V'], ['L', 'T', 'A', 'B'])

>> ['S', 'U', 'V']

Upvotes: 1

salparadise
salparadise

Reputation: 5815

Simple using zip:

def remove(l1, l2):
    return [first for first, second in zip(l1, l2) if first != second]

results in the items from first list:

remove(['S', 'T', 'U', 'V'], ['L', 'T', 'A', 'B'])
['S', 'U', 'V']

Upvotes: 1

Nick
Nick

Reputation: 31

To add to erlinska's answer, you can reduce the solution to a single line using a list comprehension and zip.

[c1 for c1, c2 in zip(l1, l2) if c1 != c2]

Note that there's a bit of an assumption that the two lists have the same length. If they have different length, zip will only return the n tuples where n is the min length of the two lists. This means that you could miss the items in l1 if there's not an item at the same index in l2.

In your code above, you will encounter an exception if l2 is shorter than l1.

Upvotes: 3

Erlinska
Erlinska

Reputation: 433

This would work, you just need to add the character from l1 to char, instead of their index:

def remove(l1, l2):
    r = []
    for char in range(len(l1)):
        if l1[char] != l2[char]:
             r.append(l1[char])
    return r

Upvotes: 4

Related Questions