Home > front end >  python del operator not working inside for loop
python del operator not working inside for loop

Time:02-11

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))

CodePudding user response:

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
  • Related