Why does it say IndexError: list index out of range?

Question:

I am a python newbie. I am in the phase of testing my code but I am quite confused why sometimes this works and sometimes it does not. As per my understanding the random.randint(0,13) this means that random numbers from 0 to 12 which is the number of my cards list.

Error im geting:

Traceback (most recent call last):
  File "main.py", line 72, in <module>
    generate_random_hand()
  File "main.py", line 32, in generate_random_hand
    computer_hand.append(cards[rand1])
IndexError: list index out of range

Here is the code:

#Init
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
computer_hand = []
player_hand = []
isContinue = True


#Generate first 2 cards of computer and player
def generate_random_hand():
  for _ in range(0,2):
    rand1 = random.randint(0,13)
    rand2 = random.randint(0,13)
    computer_hand.append(cards[rand1])
    player_hand.append(cards[rand2])

Here is the screenshot of the problem:
Image of ERROR

EDIT:
Seems like I have mistaken the functionality of
for _ in range() which does not include the 2nd argument
and the random.randint() which includes the 2nd argument. Since I cannot delete this post anymore.

Asked By: Kejer

||

Answers:

Seems you have an incorrect assumption.

A quick test gave me the following output:

>>> from random import randint
>>> randint(0,13)
3
>>> randint(0,13)
1
>>> randint(0,13)
10
>>> randint(0,13)
2
>>> randint(0,13)
12
>>> randint(0,13)
12
>>> randint(0,13)
3
>>> randint(0,13)
12
>>> randint(0,13)
6
>>> randint(0,13)
2
>>> randint(0,13)
13

So when you eventually get a 13, the exception tells you the value provided is not in the range of indices in your list of cards: 0-12

Answered By: Adam Smooch

random.randint(0,13) goes from 0 to 13.

The array only goes from 0 to 12;

change random.randint(0,13) to:

random.randint(0, 12)
Answered By: Leo Ward

I think I see your error. The list is 13 items long, so if randint generates 13, and you use cards[13], it is out of range, as indexes start from 0. In this case, you would do cards[randint(0, 12)].

Answered By: ProgramProdigy

There are 12 elements in your list, you are trying to check for the 13th element when it should be computer_hand.append(cards[rand1 – 2]) since all indexes of elements start at 0. So there are actually 0,1,2,3,4,5,6,7,8,9,10,11 elements. Therefore, there should only be a maximum of index 11.

Answered By: Kevin Perez
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.