I ran into a rather weird problem with python list appending today. I was trying to create an array whose each element would be like a C struct
. One of these elements was a list by itself. This is the problematic code:
class players:
name='placeholder'
squad=list()
teams=list()
teams.append(players())
teams.append(players())
teams[0].name="abc"
teams[1].name="xyz"
teams[0].squad.append("Joe")
for w in teams:
print(w.name)
print(w.squad)
The output I expected is:
abc
['Joe']
xyz
[]
Since I only added a member to squad
for teams[0]. But the output I get is:
abc
['Joe']
xyz
['Joe']
The name is set fine but the .append
appended it to both elements of teams
!
What causes this and how can I work around this?
The reason is that in your class definition, squad
and name
are class variables, not instance variables. When a new player
object is initialized, it is essentially sharing the same squad
variable across all instances of the player. Instead, you want to define an __init__
method for the player
class that explicitly separates the instance-specific variables.
class players:
def __init__(self):
self.name = 'placeholder'
self.squad = []
Then, when you initialize your new player
object, it has its own squad
variable. The rest of your code should work just fine now, with only the correct object's squad
being appended to.