Python: monster list need monster help, how do I fill my list the proper way?
<p>So I started with Python yesterday and for my first project I want to make monsters battle each other.</p>

<p>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.</p>

<p>Somehow my code is wrong and only gives back one single monster :(</p>

<pre><code>def create_monster(number):
    monster = [0] * number

    for i in monster:
        """monster = [ID,GENDER,NAME,HP,ATK,DEF,SATK,SDEF,AGIL,]"""

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



    return monster
</code></pre>

<p>The output of this code is for number = 3 for example</p>

<pre><code>[[3, 'Male', 'Berid'], 0, 0]
</code></pre>

<p>but should be something like this</p>

<pre><code>[[1,'Male','Berid'],[2,'Female','David'],[3,'Male','Holger']]
</code></pre>

<p>Your loop:</p>

<pre><code>for i in monster:
</code></pre>

<p>iterates over the <em>values</em> in the <code>monster</code> list. You are not getting indices, as Python loops are <a href="https://en.wikipedia.org/wiki/Foreach_loop" rel="nofollow"><em>foreach</em> constructs</a>.</p>

<p>Your list only contains the number <code>0</code>:</p>

<pre><code>monster = [0] * number
</code></pre>

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

<p>Rather than pre-build the list with zeros, just use <a href="https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types" rel="nofollow"><code>list.append()</code></a> to add new elements as you loop, and use <a href="https://docs.python.org/3/library/stdtypes.html#ranges" rel="nofollow"><code>range()</code></a> to count out how many monsters you create:</p>

<pre><code>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
</code></pre>

<p>I renamed the function and list to the plural <code>monsters</code> to indicate this is not just about 1 monster.</p>

python arrays list