1

I'm creating a school project that needs to record the events of each iteration of a subroutine in a list. However, it appends both players list. How do I stop this from happening?

For example:

class Player:

    l = list()
    def append_list(self,i):
        self.l.append(i)

p1 = Player()
p2 = Player()

for i in range(0,5):

    p1.append_list(i)
    print(p1.l)
    p2.append_list(i)
    print(p1.l)

This code outputs:

[0]
[0, 0]
[0, 0, 1]
[0, 0, 1, 1]
[0, 0, 1, 1, 2]
[0, 0, 1, 1, 2, 2]
[0, 0, 1, 1, 2, 2, 3]
[0, 0, 1, 1, 2, 2, 3, 3]
[0, 0, 1, 1, 2, 2, 3, 3, 4]
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]

but I need it to output:

[0]
[0]
[0, 1]
[0, 1]
[0, 1, 2]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]

1 Answers1

2

Use separate instance variables instead of shared class variables - that way each of your player instances has its own list instead of a shared one:

class Player:
    def __init__(self):
        self.l = []       # create a instance list l

    def append_list(self,i):
        self.l.append(i)

# other code identical

Output:

[0]
[0]
[0, 1]
[0, 1]
[0, 1, 2]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]

More:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69