Charles Charles - 1 year ago 48
Python Question

Python: monster list need monster help, how do I fill my list the proper way?

So I started with Python yesterday and for my first project I want to make monsters battle each other.

I'm still at the start and I want to fill a list with monsters I created. My monster function asks for how many monsters it should create and gives back a list with all of them.

Somehow my code is wrong and only gives back one single monster :(

def create_monster(number):
monster = [0] * number

for i in monster:

monster[i] = [monster_identifier(), monster_gender(), None]
monster[i][2] = monster_name(monster[i][1])

return monster

The output of this code is for number = 3 for example

[[3, 'Male', 'Berid'], 0, 0]

but should be something like this


Answer Source

Your loop:

for i in monster:

iterates over the values in the monster list. You are not getting indices, as Python loops are foreach constructs.

Your list only contains the number 0:

monster = [0] * number

so all i is ever set to is 0. This in turn is why you only ever alter the element at index 0, everywhere you wrote monster[i] you could have written monster[0] for the same results.

Rather than pre-build the list with zeros, just use list.append() to add new elements as you loop, and use range() to count out how many monsters you create:

def create_monsters(number):
    monsters = []   # empty list

    for i in range(number):  # loop number times
        gender = monster_gender()
        monster = [monster_identifier(), gender, monster_name(gender)]
        monsters.append(monster)  # add to the list at the end    

    return monsters

I renamed the function and list to the plural monsters to indicate this is not just about 1 monster.