Issue 14707: extend() puzzled me. (original) (raw)

Issue14707

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:29 admin set github: 58912
2013-03-12 06:20:35 terry.reedy set messages: -
2013-03-12 05:50:23 python-dev set nosy: + python-devmessages: +
2012-05-03 16:27:57 Daniel543 set messages: +
2012-05-02 16:25:36 ezio.melotti set nosy: + ezio.melottimessages: + stage: resolved
2012-05-02 16:21:59 loewis set status: open -> closednosy: + loewismessages: + resolution: not a bug
2012-05-02 16:15:15 Daniel543 create