andrew cooke wrote:
Delaney, Timothy (Tim) wrote:
Tim Chase wrote:
# swap list contents...not so much...
>>> m,n = [1,2,3],[4,5,6]
>>> m[:],n[:] = n,m
>>> m,n
([4, 5, 6], [4, 5, 6])
[...]
For these types of things, it's best to expand the code out. The
appropriate expansion of:
m,n = [1,2,3],[4,5,6]
m[:],n[:] = n,m
is:
m = [1,2,3]
n = [4,5,6]
m[:] = n
n[:] = m
[...] OTOH, for:
m,n = [1,2,3],[4,5,6]
m[:],n[:] = n[:],m[:]
the expansion is more like:
m = [1,2,3]
n = [4,5,6]
rhs1 = n[:]
rhs2 = m[:]
m[:] = rhs1
n[:] = rhs2
Maybe I'm just being stupid, but you don't seem to have explained
anything. Isn't the question: Why is the expansion different for the two
cases? Why don't both expand to have the intermediate rhs variables?
Andrew
Actually the expansion is the same for all case:
Pseudo notation:
m = `m obj`
n = `l obj`
rhs1 = `n rhs`
rhs2 = `m rhs`
`m lhs` = rhs1
`n lhs` = rhs2
where `m rhs` and `n rhs` is whatever you put on the right hand side of
the assingment; and `m lhs` and `n lhs` is whatever you put on the left
hand side of the assignment.
i.e.:
m, n = [1, 2, 3], [4, 5, 6]
m[:], n[:] = n, m
is
m = [1, 2, 3]
n = [4, 5, 6]
rhs1 = n
rhs2 = m
m[:] = rhs1
n[:] = rhs2
while:
m, n = [1, 2, 3], [4, 5, 6]
m[:], n[:] = n[:], m[:]
is
m = [1, 2, 3]
n = [4, 5, 6]
rhs1 = n[:]
rhs2 = m[:]
m[:] = rhs1
n[:] = rhs2
while:
m, n = [1, 2, 3], [4, 5, 6]
m, n = n, m
is
m = [1, 2, 3]
n = [4, 5, 6]
rhs1 = n
rhs2 = m
m = rhs1
n = rhs2
while:
m, n = [1, 2, 3], [4, 5, 6]
m, n = n[:], m[:]
is
m = [1, 2, 3]
n = [4, 5, 6]
rhs1 = n[:]
rhs2 = m[:]
m = rhs1
n = rhs2
--
http://mail.python.org/mailman/listinfo/python-list