I do not know why q acts as a pointer. The Final list L is : [13, [28, [24, [3, None]]]]
I do not understand how [3, None] is added to it.
import sys;
def main( argv=sys.argv ) :
L = [24, None]
t = [13, None]
t[1] = L
L = t
t = [28, None]
t[1] = L[1]
L[1] = t
t = [3, None]
p = L
while p != None :
q = p
p = p[1]
if p == L :
L = t
else :
q[1] = t
print L
if __name__ == "__main__" :
main()
-
4Can you reduce the code (to a working example) that contains just the operation(s) you don't understand?Lukas Graf– Lukas Graf2013年10月28日 11:47:00 +00:00Commented Oct 28, 2013 at 11:47
2 Answers 2
while you're doing
if p == L:
L = t
else:
q[1] = t
the q is actually the pointer, which is [24, None], and then you executed q[1] = t, so it will become [24, [3, None]].
at this time, the L is actually [13, [28, q]]
so it will change the most interior list in your L
1 Comment
Lists contains references to objects. If those objects are mutable, the list can appear to change when the mutable object changes. In fact, the list doesn't change, just the contents of the object being referenced. You can use the id() command to view the references and see that they do not change.
Your code is mutating the original [24, None] list. Here's some extra print statements to see what is going on:
L = [24, None] # Creates a list, which is a mutable object
print(id(L)) # Here is its unique ID.
t = [13, None]
t[1] = L
L = t
t = [28, None]
t[1] = L[1]
L[1] = t
print(L,id(L[1][1])) # Current contents of L, contains the same mutable list
t = [3, None]
p = L
while p:
q = p # q = [13, [28, [24, None]]], [28, [24, None]], [24, None]
p = p[1] # p = [28, [24, None]] , [24, None] , None
print(L,id(L[1][1])) # Here is L again, still contains the same mutable list
print(q,id(q)) # q also references the same mutable list
if p == L: # False
L = t
else:
q[1] = t # Mutate that same list!
print(L)
Output below. Note that the [24, None] list has the same ID in all cases, so when you change the None element in q, L has a reference to the same list and appears to change as well.
64809160
[13, [28, [24, None]]] 64809160
[13, [28, [24, None]]] 64809160
[24, None] 64809160
[13, [28, [24, [3, None]]]]
Here's a simpler example:
>>> q = [1,2,3] # Create a list named 'q'
>>> L = [24, q] # Put that list in L
>>> L
[24, [1, 2, 3]]
>>> q[1] = 5 # change 'q'
>>> L # L appears to change. It references the same list.
[24, [1, 5, 3]]
2 Comments
L = t; t = [28, None]? L becomes the name of the same list that t references, but then t becomes a reference to a brand new list.