List repetition - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: List repetition (/thread-3445.html) |
List repetition - ashwin - May-24-2017 my question here I was experimenting with lists and this particular behavior of python caused me some confusion. Can anyone please clarify if what i think is right. myList = [[1,2,3]] * 3 myList[0]=[1,2,3,4]now when i print myList i get the following output: [[1,2,3,4],[1,2,3],[1,2,3]] suppose i make a small change like this: myList = [[1,2,3]] * 3 myList[0].append(4)now when i print myList i get the following output: [[1,2,3,4],[1,2,3,4],[1,2,3,4]] Since all 3 lists are one single list object with 3 references is this happening because in the first case I'm actually assigning a new object to the first position and in the second case I'm modifying the object that all 3 lists are referring to? RE: List repetition - buran - May-24-2017 yes, your understanding is correct. Append modify the list in place, so you change the object that has 3 references to it. While in the former case you assign new different object to index 0. RE: List repetition - wavic - May-24-2017 Python does not duplicate an object in the memory. In [1]: a = 2 In [2]: b = 2 In [3]: id(a) Out[3]: 10914400 In [4]: id(b) Out[4]: 10914400https://www.youtube.com/watch?v=F6u5rhUQ6dU RE: List repetition - snippsat - May-24-2017 Here just some test,so can you think of we they are different. >>> lst_1 = [[1,2,3]] * 3 >>> lst_2 = [[1,2,3] for i in range(3)] >>> lst_1 [[1, 2, 3], [1, 2, 3], [1, 2, 3]] >>> lst_2 [[1, 2, 3], [1, 2, 3], [1, 2, 3]] >>> >>> lst_1[0].append(4) >>> lst_2[0].append(4) >>> lst_1 [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]] >>> lst_2 [[1, 2, 3, 4], [1, 2, 3], [1, 2, 3]] >>> >>> [id(i) for i in lst_1] [23028560, 23028560, 23028560] >>> [id(i) for i in lst_2] [65702968, 65711560, 65708120] >>> >>> help(id) Help on built-in function id in module builtins: id(obj, /) Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory address.) |