Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
boi
14,242 PointsHave trouble understanding the working and use of the COPY module, and no use of the COPY module. Python OOP
Hello there! how are you?
Here is the code;
class filled(list):
def __init__(self, count, value, *args, **kwargs):
super().__init__()
for _ in range(count):
self.append(value)
This code is used for creating any number of copies for a given value.
Now running this code in the Shell;
>>> fl = filled(3, [1, 2, 3, 4, 5])
>>> fl
#output [ [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5] ]
>>> fl [0] [4] = 100
>>> fl
#output [ [1, 2, 3, 4, 100], [1, 2, 3, 4, 100], [1, 2, 3, 4, 100] ]
I am expecting an output like [ [1, 2, 3, 4, 100], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5] ]
I understand that instead of;
self.append(value)
I should use
self.append(copy.copy(value))
To prevent changing all the lists.
BUT what I don't understand is this;
why did all of the lists change their values when I specifically or exclusively mentioned that "fl" at index " [0] [4] " ONLY needs to be changed. why did all of them change even tho I did not give an index for them.
The output should make sense If I were to do this;
>>> fl [0] [4] = 100
>>> fl [1] [4] = 100
>>> fl [2] [4] = 100
>>> fl [3] [4] = 100
>>> fl [4] [4] = 100
I just don't understand the "behind the scenes" working of this code, and why when we use copy.copy(value), the problem is completely solved.
I would really appreciate it if you could explain it with complete details please.
1 Answer
Steven Parker
243,201 PointsWithout using "copy", the inner lists are not duplicates but all references to the same list. In the example above, there is only one list of 5 numbers but "f1" contains three references to it.
So any change you make to the (one and only) inner list will be seen through each of the references (indexes) to it.