How can I see if a list contains objects that are common with another list in python?

Viewed 87

So I am making a project in python and I dont know how to check if a list contains something that the other list has as well. Like this:

list1 = [1, 2, 3, 4]
list2 = [4, 5, 6, 7]

So how can I see if list1 and list2 have an object in common like 4 ?

2 Answers

You can simply use set as a one line code.

list1 = [1, 2, 3, 4]
list2 = [4, 5, 6, 7]

print(list(set(list1) & set(list2)))

Output: 4

If you learned set theory, this will seem familiar to you.

def commonElements(list1, list2):
    result = []
    for i in list1:
        for j in list2:
            if i == j:
                result.append(i)
    return result
      

list1 = [1, 2, 3, 4]
list2 = [4, 5, 6, 7]
print(common_data(a, b))

This program loops through all the elements and checks if there are not one but all the common elements and returns them in a list

Related