>>>a=[999999,2,3]
>>>b=[999999,2,3]
>>>print(a[0] is b[0])
False#because it works for numbers -5 through 256
>>>a=[1,2,3]
>>>b=a[:]
>>>print(a[0] is b[0])
True#because it works for numbers -5 through 256
>>>a=[999999,2,3]
>>>b=a[:]
>>>print(a[0] is b[0])
True#why not False ???
what happen b=a[:] (why not works for numbers -5 through 256 )?
The [:] makes a shallow copy of the array, hence allowing you to modify your copy without damaging the original. The reason this also works for strings is that in Python, Strings are arrays of bytes representing Unicode characters.
It appears that a, b = b, a involves the one-to-one unpacking. However, it turns out that Python uses an optimized operation (i.e., ROT_TWO ) to swap the references on a stack. Such swapping happens when three variables are involved. However, tuple creation and unpacking come to play when there are four variables.
The ROT_TWO opcode swaps the top two positions on the stack so the stack now has [b, a] at the top. The two STORE_FAST opcodes then takes those two values and store them in the names on the left-hand side of the assignment.
It means bitwise AND operation. Example : x = 5 x &= 3 #which is similar to x = x & 3 print(x)
The -5 to 256 range has to do with the following:
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an
int
in that range you actually just get back a reference to the existing object.
To demonstrate this, notice how id(123)
keeps returning the same value, whereas id(9999)
can return different values:
In [18]: id(123)
Out[18]: 9421736
In [19]: id(123)
Out[19]: 9421736
In [20]: id(9999)
Out[20]: 9708228
In [21]: id(9999)
Out[21]: 10706060
This is of course an artefact of the current implementation. A different Python implementation might not do that, or might use a different range.
As to your last example:
In [14]: a=[999999, 2, 3]
In [15]: b=a[:]
In [16]: map(id, a)
Out[16]: [10908252, 9421180, 9421168]
In [17]: map(id, b)
Out[17]: [10908252, 9421180, 9421168]
As you can see, [:]
simply copies the references. This explains why a[i] is b[i]
evaluates to True
for all i
.
a = [1,2,3]
b = a
Here, b=a
makes b an alias of a. That means, all changes to b will be seen in a.
b=a[:]
means to make a copy of a and assign it to b.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With