[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Concerning copy



Nate Nichols wrote:
In my limited experience with Python/PyGame, it seems to me like list
comprehensions are a good way around this "bug".

Instead of

def main():
    nums = [x for x in range(10)]
    for num in nums:
         if num % 2 = 0:
               nums.remove(num)


That's not good. It's misleading the programmer into thinking divisibility by 2 is an important criterion. What if it was a list of objects instead of numbers, and not divisible at all?


It's better to either copy the list as in the following code:

def main():
    nums = [x for x in range(10)]
    print nums
    for num in nums[:]:
        nums.remove(num)
    print nums
main()

or iterate over its length like this:

def main():
    nums = [x for x in range(10)]
    print nums
    for i in range(len(nums)):
        del nums[0]
    print nums
main()

--Kamilche