Python Forum
Why is one duplicate not removed?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why is one duplicate not removed?
#1
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.
Reply
#2
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)
Output:
L1 = [3, 4]
Reply
#3
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.
Reply
#4
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
Reply
#5
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]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Openpyxl: Excel formula & condition formatting removed JaneTan 0 907 Sep-25-2020, 07:02 AM
Last Post: JaneTan
  How to check if video has been deleted or removed in youtube using python Prince_Bhatia 14 6,422 Feb-21-2020, 04:33 AM
Last Post: jehoshua
  can python generate lists in blocks that can be removed from the original output? teknalchemist 0 1,274 May-22-2018, 06:10 PM
Last Post: teknalchemist
  how to detect \x in string so it can be removed azimmermann 5 3,885 Jul-05-2017, 10:46 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020