Xailex
Xailex

Reputation: 29

Python 3: List index out of range

Every time I run this command, I can't get through all of the cards without having this error; IndexError: list index out of range.

import random

cards = ['2', '2', '2', '2', '3', '3', '3', '3', '4', '4', '4', '4', '5', '5', '5', '5', '6', '6', '6', '6', '7', '7', '7', '7', '8', '8', '8', '8', '9', '9', '9', '9', '10', ',10', '10', '10', 'J', 'J', 'J', 'J', 'Q', 'Q', 'Q', 'Q', 'K', 'K', 'K', 'K', 'A', 'A', 'A', 'A']

randomness = 51

while True:

    cardIndex = random.randint(0, randomness)
    del cards[cardIndex]
    randomness = randomness -1
    print(cards[cardIndex])

Upvotes: 1

Views: 164

Answers (3)

Brambor
Brambor

Reputation: 664

Your problem is that you first delete the card and then print it, so the problem is when you pick the last card:

randomness = 51

while True:

    cardIndex = random.randint(0, randomness) #random.randint(0, 51) could give num 51 so card 52
    del cards[cardIndex] # deleted 52nd card (num 51)
    randomness = randomness -1
    print(cards[cardIndex]) # there is no 52nd card (num 51) anymore

what you want is to change printing and deleting:

while len(cards) > 0: # once yours pack of card is empty you want to stop
    cardIndex = random.randint(0, randomness)
    print(cards[cardIndex])
    del cards[cardIndex]
    randomness = randomness -1

len() tell you how many things are in list It should work now :)

Upvotes: 2

vaultah
vaultah

Reputation: 46533

Print cards[cardIndex] before deleting by that index:

while cards: # Because we need to stop somewhere
    cardIndex = random.randint(0, randomness)
    print(cards[cardIndex])
    del cards[cardIndex]
    randomness = randomness -1

And you don't need randomness at all:

while cards:
    cardIndex = random.randrange(len(cards))
    print(cards[cardIndex])
    del cards[cardIndex]

You'd do that using either random.sample:

for c in random.sample(cards, len(cards)):
    print(c)

or random.shuffle (which will modify the cards list):

random.shuffle(cards)
for c in cards:
    print(c)

Upvotes: 3

f43d65
f43d65

Reputation: 2302

while cards:
    idx = random.randint(0, len(cards) - 1)
    print(cards[idx])
    del cards[idx]

Upvotes: -1

Related Questions