I am getting an IndexError
and I'm unsure why.
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
USER = []
CPU = []
selected = 1
while selected < 26:
CPU.append(cards.pop(random.choice(cards)))
USER.append(cards.pop(random.choice(cards)))
selected = selected 1
I want the items inside the list cards
to be appended into the lists USER
and CPU
. It worked originally but after working on something else it stopped working. I looked up why but the pop
index says it's out of range, but I don't understand why.
CodePudding user response:
The problem is that random.choice()
returns a random value from the list, but the argument to cards.pop()
must be an index. When the list becomes shorter than 14 elements, some of the values will be invalid indexes and you'll get an error.
A simpler way to do this is to just shuffle the cards
list and then assign half to each player.
random.shuffle(cards)
CPU = cards[:26]
USER = cards[26:]
CodePudding user response:
I'd change the while line into: while not cards
. If cards is an empty list, this returns false and exits the loop. Please keep in mind that since You're taking more than one card out of the list, this may fail if 52/(takings per iteration) gives a non-0 remainder.
CodePudding user response:
Since random.choice(cards)
returns a value from the list cards
, that means that if you pass the result into cards.pop()
, which expects you to pass in the index of an item, that means that you could potentially pass an index into the pop()
which is out of range. For instance, if your list cards
has a length of 9
at some point while you're running your script, and random.choice(cards)
happens to return 11
, then you'll get an error about the pop index.
The solution for how to pop a random item out of a list has already been covered here so I'm not going to repeat it in this answer. What is the most pythonic way to pop a random element from a list?
CodePudding user response:
As I mention in a comment, the IndexError
is because you're passing and element of the list instead of its index to the pop()
method. One way to avoid the problem would be to instead use random.randrange()
to pick a valid value to pass it:
import random
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
USER = []
CPU = []
selected = 1
while selected < 26:
CPU.append(cards.pop(random.randrange(len(cards))))
USER.append(cards.pop(random.randrange(len(cards))))
selected = 1