0

beginner python user, I have to write a function that takes as parameters two lists L1 and L2 and returns a list L3 of elements that are common to L1 and L2. For example: L1=[5,4,6,3,4], L2=[9,4,3,11], then the function returns [4,3] (an element is listed once). Now, I am able to append the elements (find my code below) which is the easy part, but I can't seem to not include the already appended elements.

def common(L1,L2):

   L3=[]
   for i in range (len(L1)):
       for j in range (len(L2)):
          if L1[i]==L2[j]:
             L3.append(L1[i])

L1=[5,4,6,3,4]
L2=[9,4,3,11]
print(common(L1,L2))

If I try to include a nested loop for L3 and a condition in the if statement, nothing gets printed.

  • 3
    `L3 = list(set(L1) & set(L2))` – Reut Sharabani Mar 06 '19 at 13:20
  • And if you want it in order (of L2), you can do `L3 = sorted(list(set(L1) & set(L2)),key = lambda x: L2.index(x))`. (just replace L2 by L1 in the lambda to return it in order of L1) Unfortunately, i can't post an answer myself because the post is marked as duplicate. – Nenri Mar 06 '19 at 13:36

1 Answers1

0

You can use the in operator to check and see if each element in L1 is in L2, but not in L3. (It also checks the entire list, so you don't have to write your own nested loop.)

L3 = []
for x in L1:
    if x in L2 and x not in L3:
        L3.append(x)
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880