Why is one duplicate not removed? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Why is one duplicate not removed? (/thread-27520.html) |
Why is one duplicate not removed? - Emekadavid - Jun-09-2020 This code removes the duplicates in two lists. But when I run it, one of the duplicates is not removed. It beats me. Can someone explain to me why. def removeDups(L1, L2): """Assumes that L1 and L2 are lists. Removes any element from L1 that also occurs in L2""" for e in L1: if e in L2: L1.remove(e) L1 = [1,2,3,4,6] L2 = [1,2,5,6] removeDups(L1, L2) print('L1 =', L1)It prints: [2,3,4] but item 2 is still a duplicate. Have run it several times and baffled. RE: Why is one duplicate not removed? - Yoriz - Jun-09-2020 You shouldn't alter a list while iterating over it, it loses track of the position, make a copy of the list to iterate and alter the original. def removeDups(L1, L2): """Assumes that L1 and L2 are lists. Removes any element from L1 that also occurs in L2""" for e in L1[:]: if e in L2: L1.remove(e) L1 = [1, 2, 3, 4, 6] L2 = [1, 2, 5, 6] removeDups(L1, L2) print('L1 =', L1)
RE: Why is one duplicate not removed? - Emekadavid - Jun-09-2020 Ok. Iterate over the copy and then remove the duplicate in the original list. Got it. I changed the code to: for i in L1[:]:and it worked. Thanks. solved. RE: Why is one duplicate not removed? - divyansh - Jun-09-2020 for more info you can watch MIT 60001 course 5th lecture on youtube you will find the same example in the last 5 min of that lecture RE: Why is one duplicate not removed? - perfringo - Jun-09-2020 Another way is to use list comprehension: >>> lst_1 = [1, 2, 3, 4, 5, 6] >>> lst_2 = [1, 2, 5, 6] >>> lst_1 = [item for item in lst_1 if item not in lst_2] >>> lst_1 [3, 4] |