Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happen b=a[:] in python?

    >>>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 )?

like image 399
Chia's JaJa Avatar asked Nov 24 '12 07:11

Chia's JaJa


People also ask

What does [:] do in Python?

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.

How does a b/b a work in Python?

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.

How does Rott 2 work in Python?

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.

What does &= mean in Python?

It means bitwise AND operation. Example : x = 5 x &= 3 #which is similar to x = x & 3 print(x)


2 Answers

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.

like image 197
NPE Avatar answered Sep 27 '22 17:09

NPE


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.

like image 30
alinsoar Avatar answered Sep 27 '22 17:09

alinsoar