Why am I getting an infinite for loop?
<p>For this python problem I am taking in one argument an int, this is the max length of a list I am going to be appending to. Starting with an int value of 1, I want to iterate through the list appending two more linear values until the max length is reached. </p>

<p>I am getting an infinite loop or something similar; I am not receiving any values but python is still processing. </p>

<p>This is the code where the infinite loop is occurring, wondering why? 
Code:</p>

<pre><code>   def dbl_linear(n):
        lst_u =[1]
        while len(lst_u)&lt;=n:
            for i in lst_u:
                lst_u.append(2*i+1)
                lst_u.append(3*i+1)
        return sorted(lst_u)

dbl_linear(10)
</code></pre>

<p>I looked up this example user had set a variable to another variable that contained a list before the for loop and then changed it back after the loop. Wondering why this is done and why it is useful?
other code:
d</p>

<pre><code>ef dbl_linear(n):
    lst_u =[1]
    while len(lst_u)&lt;=n:
        new_u = lst_u
        for i in lst_u:
            new_u.append(2*i+1)
            new_u.append(3*i+1)
        new_u=lst_u
    return sorted(lst_u)

dbl_linear(10)
</code></pre>

<p>You are adding to the list as you loop over it. A list iterator simply increments a position counter and returns the value at that index until the index doesn't exist. It doesn't keep track of the length of the list up-front. In your case, by adding more elements to the end, the iterator never reaches an index that doesn't exist.</p>

<p>You have several options:</p>

<ul>
<li><p>Create a copy of the list first to iterate over; that copy won't grow:</p>

<pre><code>def dbl_linear(n):
    lst_u = [1]
    while len(lst_u)&lt;=n:
        for i in lst_u[:]:  # [:] returns a shallow copy
            lst_u.append(2*i+1)
            lst_u.append(3*i+1)
    return sorted(lst_u)
</code></pre></li>
<li><p>Append to a <em>separate, new</em> list and extend the original after the loop:</p>

<pre><code>def dbl_linear(n):
    lst_u = [1]
    while len(lst_u)&lt;=n:
        new_values = []
        for i in lst_u:
            new_values.append(2*i+1)
            new_values.append(3*i+1)
        lst_u.extend(new_values)
    return sorted(lst_u)
</code></pre></li>
<li><p>Use a <code>range()</code> to produce indices; this is based on taking the length <em>once</em>:</p>

<pre><code>def dbl_linear(n):
    lst_u = [1]
    while len(lst_u)&lt;=n:
        for idx in range(len(lst_u)):
            i = lst_u[idx]
            lst_u.append(2*i+1)
            lst_u.append(3*i+1)
    return sorted(lst_u)
</code></pre></li>
</ul>

python loops