Python list appending issue -


i ran rather weird problem python list appending today. trying create array each element c struct. 1 of these elements list itself. 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")  w in teams:     print(w.name)     print(w.squad) 

the output expected is:

abc ['joe'] xyz [] 

since added member squad teams[0]. output is:

abc ['joe'] xyz ['joe'] 

the name set fine .append appended both elements of teams!

what causes , how can work around this?

the reason in class definition, squad , name class variables, not instance variables. when new player object initialized, sharing same squad variable across instances of player. instead, want define __init__ method player class explicitly separates instance-specific variables.

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

then, when initialize new player object, has own squad variable. rest of code should work fine now, correct object's squad being appended to.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -