-1

I am trying to find the intersection of the two lists without making them into sets in python. I need to know what is wrong in this code. Can't variables like i and y be equated? This is the code that i have written below:

l1 = [10, 20, 30, 70, 80, 69, 100, 20, 40]
l2 = [30, 50, 60, 70, 69, 40]
for i in l1:
    for y in l2:
        if y == i:
            l1.remove(i) 
print(l1)
ktzr
  • 1,625
  • 1
  • 11
  • 25
  • What are you expecting the result to be? How does the actual result differ? – Karl Knechtel Mar 08 '20 at 16:39
  • I'm marking as a duplicate because the linked question explains the most obvious issue with the approach you're trying in this code. However, there's also the logical issue that if you remove the common elements from `l1`, then `l1` will *not* end up containing the common elements, which is what I assume you want. – Karl Knechtel Mar 08 '20 at 16:45
  • 10,20,70,80,100,20 this is the answer that i am getting. It has 70 which is there in l1 and l2. – beginnercoder Mar 09 '20 at 01:05
  • I am also finding the common values. Either I can remove them from l1 or l2, when I am doing it I am getting the correct answer if i do: l2.remove(y) But when I do: l1.remove(i) I don't get the correct answer. This is what I get. [10, 20, 70, 80, 100, 20]. The 70 is in both l1 and l2 which should have been removed. is this why for loops function? – beginnercoder Mar 09 '20 at 01:10

1 Answers1

0

Close, but not quite there! You are finding the intersection of the lists correctly but you are removing those intersecting values from the first list. If you want to show the values you need to add them to a 3rd list and print that.

l1 = [10, 20, 30, 70, 80, 69, 100, 20, 40]
l2 = [30, 50, 60, 70, 69, 40]
l3 = []

for i in l1:
    for y in l2:
        if y == i:
            l3.append(i)

print(l3)
Rob P
  • 190
  • 1
  • 11
  • I am also finding the common values. Either I can remove them from l1 or l2, when I am doing it I am getting the correct answer if i do: l2.remove(y) But when I do: l1.remove(i) I don't get the correct answer. This is what I get. [10, 20, 70, 80, 100, 20]. The 70 is in both l1 and l2 which should have been removed. is this why for loops function? – beginnercoder Mar 09 '20 at 01:08