0

I would like to find the duplicated data from two different list. The result should show me which data is duplicated.

Here is the list of my data

List1 = ['a', 'e', 'i', 'o', 'u']  
List2 = ['a', 'b', 'c', 'd', 'e']  

The function

def list_contains(List1, List2): 
  
  # Iterate in the 1st list 
  for m in List1: 
    # Iterate in the 2nd list 
    for n in List2:   
    # if there is a match
      if m == n: 
        return m     
  return m
list_contains(List1,List2)

I get the result is 'a' but the result I expected is 'a','e'.

JsBoon
  • 45
  • 4

1 Answers1

1
set(List1).intersection(set(List2))

Issue with your code:

return statement will exit from the function, so at the first match it will just return with the first match. Since you need all the matches not just the first match you need to capture them into say a list and then return rather then returning at the fist match.

Fix:

def list_contains(List1, List2): 
  result = []
  # Iterate in the 1st list 
  for m in List1: 
    # Iterate in the 2nd list 
    for n in List2:   
    # if there is a match
      if m == n: 
        result += m
  return result
mujjiga
  • 16,186
  • 2
  • 33
  • 51