What is the logical error in my opinion? Which point I have missed

Screen Link: https://app.dataquest.io/m/350/guided-project%3A-profitable-app-profiles-for-the-app-store-and-google-play-markets/4/removing-duplicate-entries-part-one

My Code:

for row in android[1:]:
    name = row[0]
    num_review = int(row[3])
    if dict_by_review[name] != num_review:
        del android[android.index(row)]
print(len(android))

What I expected to happen: I expect eliminate all the duplicates

What actually happened: I haven’t got what happened but length of the list should have been 9659 but it printed 10055 after execution

Enter other details below: dict_by_review is dictionary which I created according to solution and it contains 9659 correct key

1 Like

Most likely, it’s because you are essentially deleting elements from android as you iterate through it in the for loop.

So, if you iterate through it and delete an element from it, you inadvertently mess up the next iteration. As a result, what you wish to delete might not get deleted.

For example, take the following simplified example -

a = [1, 2, 3, 4, 5, 8, 34534, 3453, 23, 32, 4, 9]

for item in a:
    if item%2==0:
        del a[a.index(item)]
print(a)

The above checks if a number in a is even or not. If it is, it removes that number. Similar to your code.

This is the output of the above -

[1, 3, 5, 34534, 3453, 23, 4, 9]

As you can see, it still contains two numbers that are clearly even.

So, don’t try to modify the list you are iterating through as you iterate through it. Try to spend some time thinking of alternative ways to approach this.

2 Likes