Python variable variable?

What happens to my python variable? old_posseems to be related to pos:

the code:

pos = [7, 7]
direction = [1, 1]
old_pos = pos
print 'pos     = '+str(pos)
print 'old_pos = '+str(old_pos)
pos[0] += direction[0]
pos[1] += direction[1]
print 'pos     = '+str(pos)
print 'old_pos = '+str(old_pos)

Conclusion:

pos     = [7, 7]
old_pos = [7, 7]
pos     = [8, 8]
old_pos = [8, 8]

However, if I replaced old_pos = poswith old_pos = tuple(pos)or even old_pos = list(pos), I will not get this problem:

pos     = [7, 7]
old_pos = [7, 7]
pos     = [8, 8]
old_pos = [7, 7]
+5
source share
5 answers

When you say old_pos = pos, you are not posmaking a copy , but simply making another link to the same list. If you want the two lists to be maintained independently of each other, you need to make a copy, for example, using a function list(pos)as you mention, or using a slice notation pos[:].

+12
source

old_pos = pos , pos, old_pos . , pos, , old_pos. "" "- " . , - , - .

3 :

old_pos = pos[:]

old_pos = list(pos)

from copy import copy
old_pos = copy(pos)

, - , . , .

+7

old_pos , pos

- :

old_pos = pos

old_pos pos . pos.

+3

. , :

>>> pos = [7, 7]
>>> old_pos = pos
>>> id(pos)
4299304472
>>> id(old_pos)
4299304472

, . , copy.

>>> from copy import copy
>>> pos = [7, 7]
>>> old_pos = pos
>>> id(pos)
4299304472
>>> id(old_pos)
4299304472
>>> old_pos = copy(pos)
>>> id(old_pos)
4299349240
+3

. , a = [[0,1,2],[3,4],[5,6,7,8]], b = a . . , . , b = [i[:] for i in a] .

0

All Articles