+ 2
Are linked variables linked for all perpertuity or for specific scenarios?
In a quiz I received the following code to find the result: list1 = [1,2,3,4]; list2 = list1; list1.append(5); print(list2) >>> [1,2,3,4,5] was the result. Now that seemed strange to me since the append happened after the assignment and I would have assumed that the changes should only occur on list1. Do they remain linked forever or is the append a special situation?
5 Respuestas
+ 7
"Reference" means that when you copy a variable containing a list, you only copy the memory address where it's stored... so modifying any referenced copy, will be effective for all referenced copy...
To make a real copy of a list ( not by reference, but cloning items, so the list would be modifiable without affecting original ), you need to use the slice notation to explicitly ask interpreter to made a deep copy:
list1 = [1,2,3,4];
list2 = list1[:];
list1.append(5);
print(list2)
>>> [1,2,3,4] is the result.
http://pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-JUMP_LINK__&&__python__&&__JUMP_LINK/
+ 5
@Amaras A:
That's a complement... as you've said the essential by giving the real answer... mine just specify what's the concept of reference, and how to workaround ;)
+ 3
list1 and list2 are actually REFERENCES to the same memory object. since they are references, change in one implies the same change in the other.
0
Are they not 2 separate lists? And therefore different?
0
Thanks visph. That's a better explanation than mine