1
x = [1,2]
for i in range(4):
    y = x[:]
    print id(y)

the results are like:

4392626008 4392835408 4392626008 4392835408

My purpose is to copy x each time and do something with a new container. My python is version 2.7.5 and OS system is Mac OS X 10.9, does it matter?

4
  • It could be that because the scope of y is only inside the for loop, and hence the memory address can be reused. Commented May 21, 2014 at 8:28
  • Why should y have a different address each time ??? What you are trying to do is unclear. Commented May 21, 2014 at 8:29
  • like I said. I need a new container Commented May 21, 2014 at 8:34
  • @AndyLiu you are getting a new container... It just happens to be re-using the address of an old one that you've informed Python it can garbage collect by not having any references to the previous created slice(s) any more Commented May 21, 2014 at 8:34

1 Answer 1

4

You're never keeping all occurrences of y around - you're just rebinding the name y to a copy of x each time in the loop, so that by a later point in the loop - Python might well choose to reallocate the same area of memory for the new slice. And since id in CPython returns the memory address, you may get the same...

for i in range(4):
    # Rebinding `y` inside the loop - making the object available for garbage collection 
    y = x[:] 
    print id(y)

If you were to keep all y about, then you will get unique ids in CPython:

>>> x = [1, 2]
>>> ys = [x[:] for _ in range(4)]
>>> map(id, ys)
[40286328, 40287568, 40287688, 40287848]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.