Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python del operator not working inside for loop

Here i want to remove duplicate objects from transaction_list. I have 7 objects in transaction_list 2 of them are duplicate. But when i run the following script it remove only one duplicate object in transaction_list. i think the issue is del operator but i don’t know how to solve this.

'''
    create list of trnasactions objects using ids
    Remove the duplicates from transaction_list
    
    current output:
        7
        6
    
    correct output:
        7
        5
'''

class Transactions:
    tid = None
    def __init__(self, tid):
        self.tid = tid

# creating transaction_list
transaction_list = []
ids = [1,2,3,1,5,5,6]
for x in ids:
    transaction_list.append(Transactions(x))

# initial length of transaction_list
print(len(transaction_list))

tmp = []

for idx,obj in enumerate(transaction_list):
    if obj.tid not in tmp:
        tmp.append(obj.tid)
    else:
        del transaction_list[idx]

# final length of transaction_list
print(len(transaction_list))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In a for loop you need to pass a copy of a list because currently you try to delete element by id and you modify the original list so next time the list has changed.

To solve it you can add : like so for idx,obj in enumerate(transaction_list[:]): and it will work like so:

class Transactions:
    def __init__(self, tid):
        self.tid = tid

# creating transaction_list
transaction_list = []
ids = [1,2,3,1,5,5,6]
for x in ids:
    transaction_list.append(Transactions(x))

# initial length of transaction_list
print(len(transaction_list))

tmp = []

for idx,obj in enumerate(transaction_list[:]):
    if obj.tid not in tmp:
        tmp.append(obj.tid)
    else:
        del transaction_list[idx]

# final length of transaction_list
print(len(transaction_list))

The output is:

7
5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading