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?
#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


Messages In This Thread
Why is one duplicate not removed? - by Emekadavid - Jun-09-2020, 02:11 PM
RE: Why is one duplicate not removed? - by Yoriz - Jun-09-2020, 02:30 PM
RE: Why is one duplicate not removed? - by divyansh - Jun-09-2020, 05:56 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Openpyxl: Excel formula & condition formatting removed JaneTan 0 3,697 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 12,007 Feb-21-2020, 04:33 AM
Last Post: jehoshua
  how to detect \x in string so it can be removed azimmermann 5 5,926 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