0

Let's say I have a python class (implementation is irrelevant), say it's class "A" as such:

>>> class A:
...     pass
...

Then for some reason, I need a list of 3 instance of class "A". I use the following syntax (multiplication operator) to create it:

>>> some_a = [A(),] * 3
>>> len(some_a)
3

Great! Looks like we have and array of tree instances of "A". But if we print the some_a array, it appears (looking at the object address) that we have 3 reference to the same instance:

>>> repr(some_a)
'[<__main__.A object at 0x7fc6fec7e290>, <__main__.A object at 0x7fc6fec7e290>, <__main__.A object at 0x7fc6fec7e290>]'

Why it the behavior as such ? What it the rational behind it ?

I was not able to find the documentation of the multiplication operator effect on lists in the python language reference, can someone point me to it ?

Antoine
  • 1,070
  • 7
  • 11
  • 2
    That's how multiplying lists work. If you want 3 different objects use `[A() for _ in range(3)]` – matszwecja Oct 18 '22 at 07:46
  • @matszwecja Yes, I figured that out. But I want to understand why it is so. – Antoine Oct 18 '22 at 07:47
  • 1
    because that's how the `*` operator is implemented for lists – DeepSpace Oct 18 '22 at 07:49
  • 1
    Before you can multiply a list, you need to actually *have* a list, so `A()` gets called and "forced" into a single value. Only then you can you can do `list * n`, and by this time list contains only a reference for the already created object. – matszwecja Oct 18 '22 at 07:51
  • Think about a list not as a list containing objects, but of addresses. each list entry points towards an object in memory. If you copy the phone number of your friend, you wont have a second friend. This pointer logic is more explicit in other languanges like C and C++. Python tries to hide this but in some instances it pops up. – Sandwichnick Oct 18 '22 at 07:52

0 Answers0