-1

I'm new to python, i was writing a functionality in which i'll have a list of values, i'll check if any value is duplicate and if its a duplicate i'm removing that from the list.

Here is the code

ds=['abhi','shek','km']
def check_duplicate(ids):
    if ids in ["abhi","shek"]:
        return True
    return False

for s in ds:
    isduplicate = check_duplicate(s)
    print("s:",s)
    if isduplicate:
        ds.remove(s)

print(ds)

in the end i expected the list to have just one value i.e ds=['km'], but it had 2 values i.e ds=['shek','km'], can you please explain why it is so?

Abhi
  • 9
  • 1

1 Answers1

1

Be really careful about editing objects you are iterating over. This kind of actions lead to unexpected behavior like the one you are showing.

Look at this code, which I modified a little bit:

ds=['abhi','shek','km']
def check_duplicate(ids):
    return ids in ['abhi', 'shek'] # if/else not needed
# ITERATE over a ds copy, which won't get modified through the loop
for s in ds.copy(): 
    if check_duplicate(s):
        ds.remove(s)

print(ds)
>> ['km']
jlgarcia
  • 333
  • 6