starship_sailor
starship_sailor

Reputation: 1

Why does this for loop run for different number of steps?

I'm trying to write a function that shuffles a deck of cards. It takes a list called cards_deck as inputs with 52 string each corresponding to a card value and shuffles the list to give the output list shuffled_deck.

Here's how I implemented it:

def shuffle_cards(card_deck):
    card_deck_temp = card_deck
    shuffled_deck = []
  
    for index in range(0,len(card_deck)):
        i = random.randint(0,len(card_deck_temp)-1)
        print(len(card_deck_temp))
        shuffled_deck.append(card_deck_temp[i])
        card_deck_temp.pop(i)
    
    return shuffled_deck

The question is: instead of looping the for in the range of 0 to 52, if I loop it as each item in the list as for index in card_deck, the loop only runs 26 times instead of 56. But the above code runs 52 times. Cannot figure out why this would happen.

Upvotes: 0

Views: 23

Answers (1)

slarag
slarag

Reputation: 418

It's because you change the size of card_deck during iteration as in you code card_deck_temp is card_deck. You need to slice (copy) the list if you want to copy it.

def shuffle_cards(card_deck):
    card_deck_temp = card_deck[:]
    shuffled_deck = []

    for index in card_deck:
        i = random.randint(0,len(card_deck_temp)-1)
        print(len(card_deck_temp))
        shuffled_deck.append(card_deck_temp[i])
        card_deck_temp.pop(i)
    
    return shuffled_deck

For simplicity you cann also just use random.shuffle:

shuffled_deck = card_deck[:]
random.shuffle(shuffled_deck)

Upvotes: 1

Related Questions