2

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?

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And some people say JavaScript is weird
0

Here's the full code [Correct One]

class players:
def __init__(self):
    self.name = 'placeholder'
    self.squad = []

teams = []
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)

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.