1

Imagine having a list like

L = [a, b, c, d]

and a class cl with an attribute at.

What I want to do is to set the to a value from that list without copying the value. For example, I want to set:

cl.at = L[1]

but the L[1] to be a shallow copy of the list L, so, if L[1] changes then cl.at changes as well.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    You can't do that in Python - if `L[1]` is immutable, then there is no way for changes to `cl.at` to alter `L`. If `L[1]` *is* mutable, then you already have the behaviour you want. – jonrsharpe Nov 01 '15 at 11:14
  • If the list is stored on the same instance you want to access the attribute on, you can make this work by defining a property `at` that gets and sets the element with index 1 in the list. If that's not your use case, please give a bit more context on what you actually want to achieve. – Sven Marnach Nov 01 '15 at 11:25
  • @jonrsharpe if i say cl.at = L[2] and L[2] is a mutable class object, will the computer copy the value of L[2] consuming memory, or it will work as a "pointer"? – Angelos Gkaraleas Nov 01 '15 at 11:26
  • 2
    @aggelosgaraleas it will work as a pointer; unless you explicitly create a copy, assignment in Python creates a reference to the same object. – jonrsharpe Nov 01 '15 at 11:27
  • 2
    @aggelosgaraleas: The accepted answer in the linked question (the "duplicate target") covers this pretty well, but you may find this article interesting: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), which was written by SO veteran Ned Batchelder. – PM 2Ring Nov 01 '15 at 11:31

0 Answers0