Repeat for i in list - n number of times
<p>After some confusion (probably if not definitely caused by a bad question asking on my part) I am trying to work how to achieve a code to perform the following operation, but n number of times:</p>

<pre><code>def 1_level:
    for i in list:
        for j in i:
            mylist.append(i)

def 2_levels:
    for i in list:
        for j in i:
            for k in j:
                mylist.append(k)

def 3_levels:
    for i in list:
        for j in i:
            for k in j:
                for l in k:
                    mylist.append(l)

def 4_levels:
    for i in list:
        for j in i:
            for k in j:
                for l in k:
                    for m in l:
                        mylist.apend(m)

def 5_levels:
    for i in list:
        for j in i:
            for k in j:
                for l in k:
                    for m in l:
                        for n in m:
                            mylist.append(n)
</code></pre>

<p>My thoughts are as below : </p>

<pre><code>def prunelist(n,mylist):
    if n &gt; 0:                          # if n has not been reached
        for i in mylist:
            templist = []              #create blank list for appended items
            for j in i:
                templist.append(j)     #append items one branch down
            mylist = templist          #overwrite original list 
            n -= 1                     #reduce n by 1 
            prunelist(n,mylist)        #perform operation again (assuming n &gt;0)

    else:
        return mylist              #when n is exhausted, output list

outputlist = prunelist(n,mylist)       #perform operation
</code></pre>

<p>(For a more rambling explanation please see edit!!!)</p>

<p>Cheers </p>

<p>J-P</p>

<p>You were almost there with your <code>prunelist</code> function, there are just a few issues:</p>

<ul>
<li>You cannot overwrite a passed list by simply doing <code>mylist = templist</code>. This does modify the <code>mylist</code> variable but not the original variable. You could replace the contents of the original list here, but a better way would be to just return the new list (i.e. <code>templist</code>). This would also fit well with the other recursion case where you return the unmodified <code>mylist</code>.</li>
<li>In every iteration through <code>mylist</code>, you throw away the result from the previous iteration. Move the <code>templist = []</code> initialization outside of the loop, and the <code>return prunelist(n, templist)</code> as well</li>
</ul>

<p>If you do that, your function already works:</p>

<pre><code>def prunelist(n, mylist):
    if n &gt; 0:
        templist = []
        for i in mylist:
            for j in i:
                templist.append(j)
        return prunelist(n - 1, templist)
    else:
        return mylist
</code></pre>

python python-3.x