Home > Software engineering >  Why is my index [4] out of range when there are 4 items in my list?
Why is my index [4] out of range when there are 4 items in my list?

Time:09-02

my error:

if player_order_chooser[4] == player_a: IndexError: list index out of range

>import random
> 
>player_a = "Joe" 
>player_b = "john" 
>player_c = "Donald" 
>player_d = "Brady"
> 
> 
>player_order_chooser = [player_a,player_b,player_c,player_d]
>random.shuffle(player_order_chooser) 
>x = len(player_order_chooser)
>print(x)
>print(player_order_chooser[1]) 
>print(player_order_chooser[2])
>print(player_order_chooser[3]) 
>print(player_order_chooser[4])

CodePudding user response:

The index of array/list starts from 0 instead of 1.

If you have array of length 4, that's mean it has values stored in indexes from 0 to 3.

In your example, without using:

random.shuffle(player_order_chooser)

In order to print "Joe" which is stored in string player_a:

>print(player_order_chooser[0])

While, in order to print "Brady" which is stored in string player_d:

>print(player_order_chooser[3])

After using random.shuffle() the results will change but the size of index remains the same.

CodePudding user response:

The index start at 0, just look at the prints and you will notice the problem:

4
john
Brady
Donald
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    print(player_order_chooser[4])
IndexError: list index out of range

The first name printed is the second that you setted.

Change your code to:

import random

player_a = "Joe" 
player_b = "john" 
player_c = "Donald" 
player_d = "Brady"
 

player_order_chooser = [player_a,player_b,player_c,player_d]
random.shuffle(player_order_chooser) 
x = len(player_order_chooser)
print(x)
print(player_order_chooser[0]) 
print(player_order_chooser[1])
print(player_order_chooser[2]) 
print(player_order_chooser[3])
  • Related