This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: extend() puzzled me.
Type: behavior Stage: resolved
Components: None Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Daniel543, ezio.melotti, loewis, python-dev
Priority: normal Keywords:

Created on 2012-05-02 16:15 by Daniel543, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (4)
msg159807 - (view) Author: Daniel543 (Daniel543) Date: 2012-05-02 16:15
Python 2.7.3 (default, Apr 20 2012, 22:44:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = ['1']
>>> b = []
>>> c = a
>>> b.append(a)
>>> a
['1']
>>> b
[['1']]
>>> c
['1']
>>> a = ['2']
>>> c.extend(a)
>>> b
[['1', '2']]
>>> c
['1', '2']
>>> a
['2']
>>> 

Is this wrong? I think the "b" should not change.
msg159808 - (view) Author: Martin v. Löwis (loewis) * (Python committer) Date: 2012-05-02 16:21
This is correct behavior, because:

>>> b[0] is c
True

(read up on the meaning of the "is" operator, if this is not a convincing proof to you).
msg159809 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2012-05-02 16:25
>>> a = ['1']
>>> b = []
>>> c = a
# now c and a refer to the same object
>>> b.append(a)
# this object is appended to b
>>> a
['1']
>>> b
[['1']]
>>> c
['1']
# a and c refer to the same object you have in b
# so all these ['1'] are actually the same object
>>> a = ['2']
# now a refers to another object
>>> c.extend(a)
# and here you are extending the object referred by c
# and the same object that you have in b
>>> b
[['1', '2']]
>>> c
['1', '2']
# so this is correct
>>> a
['2']
>>>

You can use id() to verify the identity of the objects, and read http://python.net/crew/mwh/hacks/objectthink.html for more information.
msg159866 - (view) Author: Daniel543 (Daniel543) Date: 2012-05-03 16:27
Thank u both.
History
Date User Action Args
2022-04-11 14:57:29adminsetgithub: 58912
2013-03-12 06:20:35terry.reedysetmessages: - msg184008
2013-03-12 05:50:23python-devsetnosy: + python-dev
messages: + msg184008
2012-05-03 16:27:57Daniel543setmessages: + msg159866
2012-05-02 16:25:36ezio.melottisetnosy: + ezio.melotti

messages: + msg159809
stage: resolved
2012-05-02 16:21:59loewissetstatus: open -> closed

nosy: + loewis
messages: + msg159808

resolution: not a bug
2012-05-02 16:15:15Daniel543create