List as a member of a python class, why is its contents being shared across all instances of the class?
<p>I have defined a class <code>Listener</code> and created a dictionary of <code>Listener</code> objects.  Each listener has an <code>id</code> to identify them, and a list of <code>artists</code> they listen to, <code>artists = []</code>.  Adding something to the <code>artists</code> list adds it for all instances of the <code>Listener</code> class, rather than the referred instance.  This is my problem.</p>

<p>The Listener class is defined as follows:</p>

<pre><code>class Listener:
    id = ""
    artists = []

    def __init__(self, id):
        self.id = id

    def addArtist(self, artist, plays):
        print self.id # debugging...
        print "pre: ", self.artists
        self.artists.append(artist)
        print "post: ", self.artists
</code></pre>

<p>Here is my debugging test code:</p>

<pre><code>def debug():
    listeners = {}
    listeners["0"] = Listener("0")
    listeners["1"] = Listener("1")

    listeners["0"].addArtist("The Beatles", 10)
    listeners["0"].addArtist("Lady Gaga", 4)
    listeners["1"].addArtist("Ace of Base", 5)
</code></pre>

<p>And the output:</p>

<pre><code>0
pre:  []
post:  ['The Beatles']
0
pre:  ['The Beatles']
post:  ['The Beatles', 'Lady Gaga']
1
pre:  ['The Beatles', 'Lady Gaga']
post:  ['The Beatles', 'Lady Gaga', 'Ace of Base']
</code></pre>

<p>My expected output is that the final <code>addArtist("Ace of Base", 5)</code> call would result in the output </p>

<pre><code>1
pre:  []
post:  ['Ace of Base']
</code></pre>

<p>Is this a subtlety of Python I'm not understanding?  Why is this the output and how can I get the desired output instead?  Thanks!</p>
