Skip to content Skip to sidebar Skip to footer

Python Slice Method Does Not Always Return A New Address In Memory?

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 wi

Solution 1:

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]

Post a Comment for "Python Slice Method Does Not Always Return A New Address In Memory?"