osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Weird Python Bug


2 comments:

First: Deleting from a list while you're iterating over it is a bad idea. Your first iteration gives nums[0] which is 72. But then you delete that and (in effect) everything moves up. So now the 4 is in the nums[0] slot. Your second iteration returns nums[1] which is now the 82 meaning you skipped over the 4... etc etc etc.,

Second: You are altering the original list that you're passing to the function, you're not working on a copy of it. Make sure that that is what you want, and that you didn't intend to leave the original thing alone.
>>> nums = [72, 4, 82, 67, 67]
>>> odd_ones_out(nums)
[4, 67, 67]
>>> nums
[4, 67, 67]
>>>



-----Original Message-----
From: Python-list On Behalf Of CrazyVideoGamez
Sent: Friday, September 13, 2019 3:18 PM
To: python-list at python.org
Subject: Weird Python Bug

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!
-- 
https://mail.python.org/mailman/listinfo/python-list