Inserting objects with reference to object into list
<p>I've encountered a behavior in a Python program that I've been able to condense into a smaller program. I'm pretty sure I've encountered it and solved it and the past, but can't remember how.</p>

<p>Consider the following Python program:</p>

<pre><code>import random

class B:
    def __init__(self):
        self.attr=random.randrange(0,10)

class A:
    def __init__(self):
        self.b=B()

list=[]
print "First pass"
for i in range(0,10):
    a=A()
    print "Random number in b: ",a.b.attr
    list.insert(0,a)

print "Second pass"
for l in list:
    print "Random number in b: ",a.b.attr
</code></pre>

<p>It typically outputs something such as:</p>

<pre><code>First pass
Random number in b:  9
Random number in b:  7
Random number in b:  1
Random number in b:  5
Random number in b:  9
Random number in b:  7
Random number in b:  0
Random number in b:  6
Random number in b:  2
Random number in b:  7

Second pass
Random number in b:  7
Random number in b:  7
Random number in b:  7
Random number in b:  7
Random number in b:  7
Random number in b:  7
Random number in b:  7
Random number in b:  7
Random number in b:  7
Random number in b:  7
</code></pre>

<p>How do we solve this? I know it has to do with how Python copies object etc., but having:</p>

<pre><code>import copy
list.insert(0,copy.deepcopy(a))
</code></pre>

<p>Doesn't solve it as one could expect.</p>
