What's wrong with this code?
ulrich.eckhardt at dominolaser.com
Tue Jul 24 09:47:38 CEST 2012
There is one model that has helped me much understanding how Python
ticks and that is the model of name tags. The code "a = 1" creates an
integer with value 1 and attaches a tag with "a" written on it using a
small piece of rope. Now, if you attach the tag to a different item, it
obviously doesn't change the original integer. Also, you can attach more
than one tag to the integer or even none. Further, a tag doesn't even
have to be attached to anything (this happens if you use a local
variable before assigning to it). This operation of tagging something is
done with the "=" operator.
Now, coming back to your code...
Am 23.07.2012 16:50, schrieb Stone Li:
> I'm totally confused by this code:
>> a = None
>> b = None
>> c = None
>> d = None
This adds the tags "a", "b", "c" and "d" to None.
>> x = [[a,b],
"[a, b]" creates a list, containing two anonymous tags (they don't have
anything written on them but they are accessible via index) attached to
what "a" and "b" are currently attached to . The same happens for
"[c, d]". The two lists are then put into another list with a similar
mechanism, and that list of lists is then tagged "x".
>> e,f = x
This takes the second element of "x" (the [c, d] above) and tags it with
"e" and "f". This syntax implicitly unpacks the list so the assignment
operator adds the two tags "e" and "f" to the first and second element
referenced by that list. Both "e" and "f" finally end up attached to "None".
>> c = 1
>> d = 2
These two remove the rope attaching "c" and "d" to "None" and instead
attach them to the integers "1" and "2".
I hope your Python's behaviour makes sense to you now!
 Note that in almost all cases, when referring to a tag, Python
implicitly operates on the object attached to it. One case (the only
one?) where it doesn't is the "del" statement.
More information about the Python-list