Hi guys, could you tell me how to solve this problem. This is what i've done.
The result show :
[9, 2, 6]
[3, 9, 5]

l1 = [4,9,2,6]
l2 = [3,9,4,5]
i = 0
j = 0

while(i < len(l1)):
    while(j < len(l2)):
        if(l1[i] == l2[j]):
            del(l1[i])
            del(l2[j])
        j += 1
    i += 1

print(l1)
print(l2)

Nice try. The reason that your code does not properly work is because when you delete a item in the list, you are decreasing the index of all the higher index by one then you increase the searching index by one also. So, you will skip some elements.

To solve this, you need to do it the reverse order.

l1 = [4,9,2,6]
l2 = [3,9,4,5]

i = len(l1) - 1
while(i >= 0):
    j = len(l2) - 1
    while(j >= 0):
        if (l1[i] == l2[j]):
            del(l1[i])
            del(l2[j])
        j -= 1
    i -= 1

print(l1)
print(l2)

However, there is still flaw in this code. For example, [9, 9, 1] and [2, 9]. The first list has more number 9 than the second list. The above code will only remove one 9. There is slightly better way to do this using dictionary to decide which number is duplicated in both list and remove later.

l1 = [4,9,9,2,6]
l2 = [3,9,4,5]
d = {}

for x in l1:
    d[x] = d.get(x, 0) | 1

for x in l2:
    d[x] = d.get(x, 0) | 2

l1 = [x for x in l1 if d.get(x,0) != 3]
l2 = [x for x in l2 if d.get(x,0) != 3]

print(l1)
print(l2)
commented: Thank you for the quick replay. I learn something new from you (using dictionary) +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.