2

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 ?

a human
  • 31
  • 6

2 Answers2

3

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.

Maximilian Freitag
  • 939
  • 2
  • 10
  • 26
0
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

Ruthvik
  • 790
  • 5
  • 28
  • Please don't copy and paste code from another answer/website. – Thierry Lathuille Nov 14 '21 at 17:05
  • That's why I have mention to refer that website – Ruthvik Nov 14 '21 at 17:05
  • Please don't anyway, see for example https://meta.stackoverflow.com/questions/311662/what-to-do-with-answers-that-are-copy-and-paste-of-other-answers-here – Thierry Lathuille Nov 14 '21 at 17:07
  • Ok is it good if i edit the answer and add my custom program? (I promise not the same one) – Ruthvik Nov 14 '21 at 17:08
  • The question has been closed, there are tons of duplicates for this already, so you should rather not... ;) – Thierry Lathuille Nov 14 '21 at 17:10
  • See i have changed my answer. – Ruthvik Nov 14 '21 at 17:11
  • 2
    1/ votes are anonymous, for good reason, so never imagine that anyone is the one who up or down voted your post. 2/ comments are for discussions on the technical aspects of the post, and requests for votes are seriously frowned upon here. 3/ This answer is inefficient, as it is O(len(list1) x len(list2)) even in the most favorable case, so I wouldn't recommend it. Lots of better, more efficient answers are provided in the duplicates. – Thierry Lathuille Nov 14 '21 at 17:28