0

I'm making 10 coin objects from the class MakeCoin. I put all the coin objects on the coinlist[].

I've also made a method in class MakeCoin, named pickup, this class will delete the object from the coinlist[].

In the second last part of the program I iterate over the coinlist[] with coin, and I delete the coin object name from the coinlist[] with the method pickup(). It is deleting coins from the coinlist[] but still 5 coin object names remain in the list (the even ones) - I really don't understand why they stay on the list, and how can I delete the whole list ?

from random import randint

class MakeCoin(object):
    def __init__(self,sprite):
        #give the coin random x,y location
        self.x=randint(0,10)
        self.y=randint(0,10)
        self.sprite=sprite

    def show(self):
        #show the coin location
        print "x:%d y:%d" %(self.x,self.y)

    def pickup(self):
        #you've picked up this coin, so delete it from list
        coinlist.remove(self)

#generate 10 coins  
coinlist=[]
for x in range(0,10):
    coinlist.append(MakeCoin(1))

#this will show that there are 10 coins in list 
print len(coinlist)


#this will let you pickup all the coins from the list(remove coins from coinlist) 
for coin in coinlist:
    #delete the coin !
    coin.pickup()

#in my opinion, this should print out 0 ...but it say's 5 ! (there -
#are still five coins on the list, the evencoins are still there...how to solve this ?
print len(coinlist)
Jamie Taylor
  • 4,709
  • 5
  • 44
  • 66
Lenlux
  • 41
  • 5
  • 5
    Don't remove from a list while iterating it. – tobias_k Mar 27 '14 at 13:56
  • tobias_k is right. Instead, you should reassign a filtered version of the list to the variable that held it originally. – Asad Saeeduddin Mar 27 '14 at 13:57
  • 1
    And you really should restructure your code. Classes should not have methods to modify external lists. – Jayanth Koushik Mar 27 '14 at 14:03
  • the pickup method will check later if the players x,y coordinates are in the x,y coordinated of the coin, and if so, the coin gets pickup'ped - and it will delete itself from the list, and delete the object. Sorry if i'm doing a bit clumsy, i'm just learning python with pop :-) - what would be a better idea for this ? Thanks ! – Lenlux Mar 27 '14 at 14:29

2 Answers2

1

The issue is that you are modifying the list you are iterating over. This is a bad idea. One simple way to avoid this is to make a new list like this:

for coin in coinlist[:]:
    coin.pickup()
Jayanth Koushik
  • 9,476
  • 1
  • 44
  • 52
1

You are modifying the list while iterating over it. Bad Idea.

Try this instead:

for i in range(len(coinlist)):
    coinlist[0].pickup()

OR as @Asad said

while coinlist:
    coinlist[0].pickup()
sshashank124
  • 31,495
  • 9
  • 67
  • 76