Chia's JaJa
Chia's JaJa

Reputation: 145

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

Upvotes: 9

Views: 6284

Answers (4)

alinsoar
alinsoar

Reputation: 15803

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.

Upvotes: 6

NPE
NPE

Reputation: 500773

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.

Upvotes: 12

Shep
Shep

Reputation: 8380

Adding to @NPE's answer, here's a nice illustration:

a = range(-7, 259)
b = range(-7, 259)
for x, y in zip(a,b): 
    print x, x is y

prints:

-7 False
-6 False
-5 True
-4 True
...
255 True
256 True
257 False
258 False

Upvotes: 2

jimhark
jimhark

Reputation: 5046

 >>>b=a[:]

Makes a shallow copy of the items in list a and names that copy b. All the items contained in the new list will have have the same object ids (think pointers) as the items in the original list . This is expected behavior.

Upvotes: 3

Related Questions