Python: A class attribute is being copied to all my instances of that class in a for-loop

Multi tool use


Python: A class attribute is being copied to all my instances of that class in a for-loop
I have a class called Station
...
Station
class Station():
def __init__(self):
self.connecting_stations =
...a list with 3 Station
instances...
Station
stations = [Station() for n in range(3)]
...and a for-loop that appends the string "New Hampshire"
to the connecting_stations
attribute of my three Station
instances.
"New Hampshire"
connecting_stations
Station
for station in stations:
station.connecting_stations.append("New Hampshire")
When I print([station.connecting_stations for station in stations])
it prints:
print([station.connecting_stations for station in stations])
[
["New Hampshire", "New Hampshire", "New Hampshire"],
["New Hampshire", "New Hampshire", "New Hampshire"],
["New Hampshire", "New Hampshire", "New Hampshire"]
]
...i.e. the connecting_stations
attribute of all of my Station
instances have the same "New Hampshire"
repeated 3 times.
connecting_stations
Station
"New Hampshire"
But what I really wanted to do is:
>>> print(stations[0].connecting_stations)
["New Hampshire"]
>>> print(stations[1].connecting_stations)
["New Hampshire"]
>>> print(stations[2].connecting_stations)
["New Hampshire"]
...i.e. I want each one of my Station
instances to have one -- only one -- connecting station, which is called "New Hampshire"
, but actually they're getting 3 "New Hampshire"
strings each.
Station
"New Hampshire"
"New Hampshire"
How is that even possible? What is happening and how can I solve my problem?
Note: Sorry for the bad title. Did not find better and shorter words to describe my problem.
[Station()] * 3
Are you sure the code you've shown is what you're running? Double check that you've saved the latest version and you're running it, not an older version. The issue you describe could be caused by either the
Station
instances or the list within them being references to the same object, but the code you've shown wouldn't cause that to happen.– Blckknght
27 secs ago
Station
1 Answer
1
Seems like you're not adding 3 different instances of your class to the list, but the same instance, and then when you modify it 3 times, you get "New Hapmshire" added to this same instance 3 times.
Try to replace:
for station in stations:
station.connecting_stations.append("New Hampshire")
with
stations[0].connecting_stations.append("New Hampshire")
and print your list again to see =)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
No, it really doesn't. Literally copy-paste your code, it does work the way you want. I bet the code you're having problems with is different. I even bet I know how it's different:
[Station()] * 3
, right?– John Zwinck
13 mins ago