Reputation: 203
I have created a dictionary where the entries are lists like this:
new_dict
{0: ['p1', 'R', 'p2', 'S'], 1: ['p3', 'R', 'p4', 'P'], 2: ['p5', 'R', 'p6', 'S'], 3: ['p7', 'R', 'p8', 'R'], 4: ['p9', 'P', 'p10', 'S'], 5: ['p11', 'R', 'p12', 'S'], 6: ['p13', 'S', 'p14', 'S']}
From here I am trying to check that the elements inside the lists are in my list below Moves
. For example, in new_dict[0], I want to check that the 1st element and the third element in Moves
, if not, raise the class exception. (This is a snippet of the code.)
class NoStrategyError(Exception): pass
j=0
while j < len(new_dict):
i = 0
while i < 4:
# Write the code for the NoSuchStratgyError
Moves = ['R', 'S', 'P', 'r', 's', 'p']
if new_dict[j][1+4*i] not in Moves or new_dict[j][3+4*i] not in Moves:
raise NoStrategyError("No such strategy exists!")
i+=1
j+=1
Now here is the problem, when I run this, I get the following error:
if new_dict[j][1+4*i] not in Moves or new_dict[j][3+4*i] not in Moves:
IndexError: list index out of range
What does this mean?
Is there a better way to write the inner while loop
? And change it instead to a for loop
? Something like, for elem in new_dict[j]
?
Upvotes: 0
Views: 9146
Reputation: 1970
Notice that in the first interation of your nested loop, we see the following values that are both in Moves:
>>>new_dict[0][1], new_dict[0][3]
('R', 'S')
However, on your second iteration in the nested loop, you are trying to evaluate terms that are not included in the dictionary:
>>>new_dict[1][5], new_dict[1][7]
IndexError: list index out of range
Notice that new_dict[1] only has 4 elements:
>>>new_dict[1]
['p3', 'R', 'p4', 'P']
So you can only reference new_dict[1][0],new_dict[1][1],new_dict[1][2],new_dict[1][3]:
>>>new_dict[1][0],new_dict[1][1],new_dict[1][2],new_dict[1][3]
('p3', 'R', 'p4', 'P')
Upvotes: 1