This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author steven.daprano
Recipients cmaliwal, remi.lapeyre, steven.daprano
Date 2020-05-28.17:04:50
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1590685490.19.0.339477446481.issue40809@roundup.psfhosted.org>
In-reply-to
Content
Rémi is correct, this is not a bug.

The problem isn't with list.count. If you print list.count each time through the loop, you will see that it is working perfectly. 

The problem is that you are modifying the list as you are iterating over it. That means that you skip every second item. It isn't easy to see when all the items are the same, but we can alternate int and float values (which are equal) to see how every second value is skipped.


py> a = [1, 1.0, 1, 1.0, 1, 1.0, 1, 1.0]
py> for i in a:
...     print(a, i, a.count(i))
...     if a.count(i) > 1:
...             a.remove(i)
...
[1, 1.0, 1, 1.0, 1, 1.0, 1, 1.0] 1 8
[1.0, 1, 1.0, 1, 1.0, 1, 1.0] 1 7
[1, 1.0, 1, 1.0, 1, 1.0] 1 6
[1.0, 1, 1.0, 1, 1.0] 1 5
py> a
[1, 1.0, 1, 1.0]


Notice that every one of the float 1.0 values gets skipped. That's because when you resize the list as you walk over it, the value which *would have been* the next value gets pushed back into the current position, and then you advance to the next position, and skip it.

So there's no bug in list.count, it is working perfectly each time. There's no bug in iteration either, it is walking the list correctly too. But there is a bug in your code: you are shrinking the list while walking over it, so on each step, you delete one item from the from and step forward, so you skip items.

The lesson here is not to delete items from a list while you are iterating over it.

Technically, it's okay to delete items so long as they are *ahead* of the current item, but not if they are *behind* it. But it is easiest to just use the rule, never delete items while iterating over the same list.

If you must delete items from a list, iterate over a copy.
History
Date User Action Args
2020-05-28 17:04:50steven.dapranosetrecipients: + steven.daprano, remi.lapeyre, cmaliwal
2020-05-28 17:04:50steven.dapranosetmessageid: <1590685490.19.0.339477446481.issue40809@roundup.psfhosted.org>
2020-05-28 17:04:50steven.dapranolinkissue40809 messages
2020-05-28 17:04:50steven.dapranocreate