[issue12951] List behavior is different
Amaury Forgeot d'Arc amaur...@gmail.com added the comment: See also http://docs.python.org/faq/programming.html#how-do-i-create-a-multidimensional-list -- nosy: +amaury.forgeotdarc ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12951 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12951] List behavior is different
New submission from शंतनू shanta...@gmail.com: URL: http://docs.python.org/library/stdtypes.html Following example is given. lists = [[]] * 3 lists [[], [], []] lists[0].append(3) lists [[3], [3], [3]] Behavior is as follows. a = [[]] * 3 a [[], [], []] a[0] = 1 a [1, [], []] Python interpreter details: $ python Python 2.7.2 (default, Aug 22 2011, 13:53:27) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type help, copyright, credits or license for more information. -- assignee: docs@python components: Documentation messages: 143793 nosy: docs@python, शंतनू priority: normal severity: normal status: open title: List behavior is different type: behavior versions: Python 2.7 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12951 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12951] List behavior is different
Ezio Melotti ezio.melo...@gmail.com added the comment: I don't see where is the bug. If you do lists = [[]] * 3 lists [[], [], []] you are creating a list that contains 3 references to the same list, as you can see here: lists[0] is lists[1] is lists[2] True [id(l) for l in lists] [33714832, 33714832, 33714832] so if you append an element to either of the inner list, it will show up 3 times, because the 3 lists are really the same object: lists[0].append(3) lists [[3], [3], [3]] However, if you do lists[0] = 1 lists [1, [3], [3]] you are replacing the first element of 'lists' with the int 1. This doesn't mutate the inner list, and therefore the second and third elements are not affected. See also http://python.net/crew/mwh/hacks/objectthink.html -- nosy: +ezio.melotti resolution: - invalid stage: - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12951 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com