Reputation: 10961
In python, two different variables can represent the same object. Observe:
>>> list1=['This is list1.']
>>> list2=list1
>>> list2[0] = 'This is actually list2 not list one.'
>>> print list1
['This is actually list2 not list one.']
Here is a link to this code. As you can see, there is no list1 or list2, just one list with two names. I am well aware of this effect, and I remember from a book that this is intentional, but I forget what the phenomenon is called. Also, it is occasional the source of bugs, and other languages do not have this problem. I do have a feeling that certain things having to do with objects would break though without it. What are the specific benefits of this (since python is all I really know.)
Upvotes: 3
Views: 209
Reputation: 363838
This is usually called having multiple references to a single object. The number of references is called the refcount.
In the case of recursive data structures (trees, linked lists) it may also be called structure sharing.
What are the specific benefits of this
That you don't have to copy a value to pass it to a function. Say you have a function
def print_list(l):
print("I see %d elements:" % len(l))
for x in l:
print(x)
When you pass a list to this function, what is actually passed is only a reference to the list rather than a copy of the list's contents. Similarly, methods like append
, extend
, sort
etc. are hard to implement without this feature; they'd have to construct and return new lists all the time. The same goes for any function or method that changes a data structure in-place.
When you're doing multithreaded programming, sharing of data structures is in fact a common way of setting up communications: multiple threads would reference a common Queue
that they use to pass messages around.
other languages do not have this problem
In all languages, except purely functional ones, this may be a problem. In C, C++, Go and Pascal, it can happen with pointers, in Prolog with inadvertent unification and in Java it works the same as in Python.
Upvotes: 5