Roelland Roelland - 1 month ago 10
Python Question

"ValueError: list.remove(x): x not in list", due to random numbers?

I'm writing a function to take a new card from a deck of cards, given that there are already some cards out of the deck.

def trekken(getrokken = []):
import itertools
import random

getrokken = list(getrokken)
kind = 'HCDS'
value = '123456789XJQKA'
deck = ["".join(card) for card in itertools.product(value,kind)]
for i in range(0, len(getrokken)-1): deck.remove(getrokken[i])
return(deck[(random.randint(1, len(deck)))])

When I use this for some examples a few times I sometimes get the error message:

line 16, in trekken
print(deck[(random.randint(1, len(deck)))])
IndexError: list index out of range

For example with the following input:

trekken(['6H', '3C', '3D', '8C', 'AD', '9D', '7D', 'QC'])

Maybe not the first time, but after a few tries (max. 20) I always get this error message.


In Python random.randint(low, high) will also yield high, thus len(deck) might not be a good candidate for high, better choose a value smaller by one so try instead as last line:

return deck[random.randint(0, len(deck)-1)]

Or even more clear - as @jonrsharpe suggests:

return deck[random.randrange(len(deck))]

... or as Martijn Pieters suggests:

return random.choice(deck)

Note: The list index in Python starts at 0 not 1 as in other languages like R.