Remove items from lists that doesn't match two lists

Question:

I didn’t know how to properly define this question, but here’s the problem.

I have two lists like this:

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday']
z = ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

I’d like to match up the two lists and remove any items that do not exist in both lists. That means that the output would in this case be:

y = ['Wednesday', 'Thursday']

I tried using the zip() function but couldn’t get it to work. Do you have any ideas?

Thanks beforehand.

Asked By: Eliahs Johansson

||

Answers:

bar = [ 1,2,3,4,5 ]

foo = [ 1,2,3,6 ]

returnNotMatches( a,b )

would return:

[[ 4,5 ],[ 6 ]]
Answered By: Harshit Dhiman

It is called intersection:

If you want to find element which is present in both list you can use following snippet:

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday']
z = ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

result = set(x).intersection(set(z)) 

print(result)

output

{'Thursday', 'Wednesday'}
Answered By: krisskad

Do this:

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday']
z = ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
res = list(set(x)&set(z))
print(res)

This would give you the desired result

Answered By: BishwashK

one can easily do it with list comprension:

y = [i for i in z if i in x]
Answered By: Indiano

A one-liner way to do it (however not efficient if the lists are huge), is to turn the lists into sets to get the intersection, then you can use that to start removing items from your sets.

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday']
z = ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
y = set(x).intersection(set(z))
Answered By: Fawaz.D

Code:-

def method1(lst1, lst2):
    lst3 = [value for value in lst1 if value in lst2] #List Comprehension
    return lst3

def method2(lst1, lst2):
    return list(set(lst1) & set(lst2)) #Using set and & operator

def method3(lst1, lst2):
    temp = set(lst2)       #Using hybrid list [temporary list] 
    lst3 = [value for value in lst1 if value in temp]
    return lst3

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday']
z = ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print(method1(x,z))
print(method2(x,z))
print(method3(x,z))

Output:-

['Wednesday', 'Thursday']
['Thursday', 'Wednesday']
['Wednesday', 'Thursday']
Answered By: Yash Mehta
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.