0

I have a list where I want to move the elements with '1' to the end of the list.

For example, I have the list: Test = [['dogs',2], ['cats', 3], ['dogs',4] , ['dogs', 1], ['cats', 11], ['cats',1], ['birds',1], ['birds', 12]]

I want to move all lists with a "1" as their second element to the end of the list "Test". So far,

def score_hand(hand):

#Setting the appropriate values for the cards and moving the ones to the back

for card in hand:
    if hand[hand.index(card)][1] == 1:
        hand.append(card)
        hand.remove(card)

However, when doing this, my loop skips an element. I'm a new coder and I'm unsure of what to do.

MT0820
  • 21
  • 1
  • 2

1 Answers1

0

I'm not sure about the implementation details in python, but modifying a list as your iterating over it is dangerous in most languages; put simply, the thing that's keeping track of where you are in the list might get confused.

One possible solution would be to store a list of the elements that end in 1 and then do all of the removing/appending in a second loop.