Weird Python Bug

MRAB python at mrabarnett.plus.com
Fri Sep 13 15:57:17 EDT 2019


On 2019-09-13 20:17, CrazyVideoGamez wrote:
> For some reason, if you put in the code
> 
> def odd_ones_out(numbers):
>      for num in numbers:
>          count = numbers.count(num)
>          if not count % 2 == 0:
>              for i in range(count):
>                  numbers.remove(num)
>      return numbers
> 
> nums = [72, 4, 82, 67, 67]
> print(odd_ones_out(nums))
> 
> For some reason, it outputs [4, 67, 67] when it should have deleted the 4 because it was odd. Another interesting thing is that when you put print(num) in the for loop, the number 4 never shows up and neither does the last 67. Help!
> 
Here's a simpler example to show what's going on:

 >>> numbers = [1, 2, 3]
 >>>
 >>> for n in numbers:
...     numbers.remove(n)
...
 >>> print(numbers)
[2]

The 'for' loop steps through the list, one item at a time: first, 
second, third, etc.

In the first iteration, the first item is 1.

The body of the loop removes that item, and the following items are 
shifted down, leaving [2, 3].

In the second iteration, the second item is 3. (2 is now the first item, 
and as far as it's concerned it has already done the first item.)

The body of the loop removes that item, and the following items are 
shifted down, leaving [2].

It has now reached the end of the list.

And the moral is: don't change a list while you're iterating over it.

Iterate over the "input" list and build a new "output" list to hold the 
results.



More information about the Python-list mailing list