1

Hello im trying to create a game but I don't know why I get "IndexError: list index out of range"

To see the error you have first to input E then 1 then C then 1 and I want to make the list E=[] and C=[] but I can't

Thanks for your help this is my code:

import random
x=0
B=['E','C','D','T']
E=[1]
C=[1]
D=[]
T=[]

Inicio=input('Presiona enter para iniciar el juego!!!')
#random.shuffle(E)
#random.shuffle(C)
#random.shuffle(D)
#random.shuffle(T)
def ocultar(lista):
  nueva_lista = []
  for e in range(len(lista)):
    nueva_lista.append('*')
  return nueva_lista


while x==0:
    print('E=',ocultar(E))
    print('C=',ocultar(C))
    print('D=',ocultar(D))
    print('T=',ocultar(T))


    Coordenadas1 = input('Ingrese la lista 1: ')
    Coordenadas2 = input('Ingrese la posicion 1: ')
    Coordenadas3 = input('Ingrese la lista 2: ')
    Coordenadas4 = input('Ingrese la posicion 2: ')
    listas = {'E': E, 'C': C, 'D': D, 'T': T}
    pos1 = int(Coordenadas2)
    pos2 = int(Coordenadas4)
    if listas[Coordenadas1][pos1] == listas[Coordenadas3][pos2]:
      (listas[Coordenadas1]).remove(listas[Coordenadas1][pos1])
      (listas[Coordenadas3]).remove(listas[Coordenadas3][pos2])
    if len(E)==0 and len(C)==0 and len(D)==0 and len(T)==0:
        x=x+1
print("Ganaste!!!")
  • 1
    Hi, it's the line `(listas[Coordenadas1]).remove(listas[Coordenadas1][pos1])`. I think you'll find the solution to your problem [here](https://stackoverflow.com/a/11520540/2454357) – Thomas Kühn May 26 '17 at 05:29
  • I get the same error with del(listas[Coordenadas1][pos1]) and del(listas[Coordenadas3][pos2]) – Carlos Sanchez May 26 '17 at 05:35
  • 1
    Most likely because you use `1` as index, but list indexing in python starts from `0`, so try `(listas[Coordenadas1]).remove(listas[Coordenadas1][pos1-1])`. This is actually already a problem in the line before. – Thomas Kühn May 26 '17 at 05:37
  • I also thought that was that but I tried -2 -1 +1 +2 and same error don't know why. Thanks – Carlos Sanchez May 26 '17 at 05:41
  • can you maybe add the error message that you get to your question? – Thomas Kühn May 26 '17 at 05:42

1 Answers1

0

List index is out of range, as you are trying to access the 1st element in the list, using index=1. As 1st element have index 0, you are getting the error. You can fix it like:

pos1 = (int(Coordenadas2) - 1)
pos2 = (int(Coordenadas4) - 1)
upaang saxena
  • 779
  • 1
  • 6
  • 18