0

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

3
  • 1
    Did you try transaction_list.pop(idx) or transaction_list.remove(obj) Commented Feb 11, 2022 at 12:06
  • 1
    @SohamGhosh that won't work because there are duplicate list items Commented Feb 11, 2022 at 12:06
  • 2
    Don't modify a loop you're currently iterating over. Commented Feb 11, 2022 at 12:12

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.