I get an IndexError
in python code.
This is the code :
n = int(input())
cardp_1 = [input() for i in range(n)]
warcount=0
m = int(input())
cardp_2 = [input() for j in range(m)]
while cardp_1 != [] or cardp_2 != []:
# print(cardp_1[0],cardp_2[0])
c1 = cardp_1[0]
c2 = cardp_2[0]
res = stronger(c1, c2)
if res == 1:
cardp_1.remove(c1)
cardp_2.remove(c2)
cardp_1.append(c1)
cardp_1.append(c2)
elif res == 2:
cardp_1.remove(c1)
cardp_2.remove(c2)
cardp_2.append(c1)
cardp_2.append(c2)
if cardp_2 == []:
print('2', warcount)
else:
print('1', warcount)
The program should run just fine, instead, it is giving IndexError
:
Traceback (most recent call last): File
"C:/Users/risha/PycharmProjects/HelloWorld/cards_war.py", line 9, in
<module>
c2 = cardp_2[0] IndexError: list index out of range
The strange part is, I tried printing the values of c1
and c2
within the while-loop, and it gets printed for every iteration.
This loop:
while cardp_1 != [] or cardp_2 != []:
says to keep iterating so long as either array is not empty, but then the first thing you do it take the first element from both. If one array is empty, you will hit the very error you describe.