I have a nested data structure (e.g. mydict[names[num]]) which is difficult to read in code. Hence I would like to create a proxy (alias) and use it to modify this structure.
long_name = [1,2,3] short = long_name assert id(long_name) == id(short) short.append(4) assert id(long_name) == id(short) short = [n**2 for n in short] assert id(long_name) == id(short) # AssertionError
Given the AssertionError on id(a) = id(b), do I understand correctly python separates short and long_name during comprehension and allocates separate memory?
In practice, my structure contains millions of long strings, so takes up a lot of space (memory), hence this concern.
Advertisement
Answer
When long_name and short are associated with the same object, you can call its methods as many times as you like and both variables will not change, but comprehension will create a new object and you will link your short variable to it. Now you have 2 variables associated with 2 different objects and 2 different links.