IndexError: list assignment index out of range Python 3

zwerg4 picture zwerg4 · Oct 8, 2017 · Viewed 21.3k times · Source

Someone has a Idea why i get an IndexError in this code?

            global gegner
            global gegnerhp
            gegner = []
            gegberhp = []



            for i in range(1,anzahlgegner):
                random = randint(1,5)
                if random == 1:
                    gegner[i] = "goblin"
                    gegnerhp[i] = randint(10,50)
                elif random == 2:
                    gegner[i] = "ghost"
                    gegnerhp[i] = randint(10,50)
                elif random == 3:
                    gegner[i] = "hound"
                    gegnerhp[i] = randint(10,50)
                elif random == 4:
                    gegner[i] = "wolf"                        #LINE 147
                    gegnerhp[i] = randint(10,50)
                elif random == 5:
                    gegner[i] = "goblin"
                    gegnerhp[i] = randint(10, 50)
                print("* {0} with {1} HP".format(gegner[i]),gegnerhp[i])

For example when random is 4 i get the following error:

  File "C:/Users/Fabio/PycharmProjects/test\dungeon.py", line 147, in run
gegner[i] = "wolf"
  IndexError: list assignment index out of range

Maybe my declaration of the list/arrays is wrong?...

Answer

http_error_418 picture http_error_418 · Oct 8, 2017

There are a number of misconceptions here, and I don't think that addressing just the one you've specifically asked about will be properly helpful, so I'm going to do more than that.

First of all, lists. You're creating empty lists gegner and gegnerhp; it looks like you then want to add some items to those lists, and you're trying to do it by specifying an index. In python, the list index starts from 0, not 1.

i.e. in the following list:

>>> gegner = ["wolf", "hound", "goblin"]
>>> print(gegner[0])
wolf
>>> print(gegner[1])
hound

The index '1' is the second item in the list.

In your code, your range(1,anzhalgegner) would start at 1 and increment up to whatever you have set anzhalgegner to be. In your first iteration, your code attempts to assign a value to the list gegner at position 1 - however, the list does not have anything at position 0, meaning it can't assign anything to position 1.

The simplest change to get you started would be to start your range from 0.

Once you've tried that out, I would also suggest that instead of manually specifying what position in the list to place an item (list[index] = value), since all you are doing is adding things to the end of the list, consider using the append method. Then it would look something like this:

if random == 1:
    gegner.append("goblin")
    gegnerhp.append(randint(10,50))