With the following code I'm trying to append all cards form the deck to the hand that have the "Cool" Key in their dictionary.
But for some some reason it only draws 2 out of 3 attacks. Can anybody explain to me what is happening?
attack = {"Name":"Attack","Cool":True}
defend = {"Name":"Defend"}
deck = [attack,attack,defend,defend,defend,attack]
hand = []
for card in deck:
try:
if card["Cool"] == True:
hand.append(deck.pop(deck.index(card)))
except Exception as e:
print (e)
print(hand)
#this Print will show that it has only appended 2 of the 3 attack dictionaries.
I've also tried this with a while loop thinking that I have messed something up with the index logic but to no avail:
EDIT: So thanks to @Chrispresso I was able to wrap my head around how to make the while loop work! I've edited that part in the code
i = 0
while i < len(deck):
try:
if deck[i]["Cool"] == True:
hand.append(deck.pop(i))
i += 1 #commenting out this line does the trick as you should not be increasing the index when you are popping something from the list as this basically makes you jump two places instead of one.
except Exception as e:
i += 1
print (e)
Thanks so much for your help in advance! EDIT: So the desired output would be
print(hand)
#[{"Name":"Attack","Cool":True},{"Name":"Attack","Cool":True},{"Name":"Attack","Cool":True}]
but currently the output is:
print(hand)
#[{"Name":"Attack","Cool":True},{"Name":"Attack","Cool":True}]