Manipulating index value, what is wrong with this code? - 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: Manipulating index value, what is wrong with this code? (/thread-24225.html) |
Manipulating index value, what is wrong with this code? - Emun - Feb-05-2020 I want to manipulate an index value on list1, but can't figure out why the manipulation('alt') appears at two locations instead of just one. list2 shows correctly what I want to do on list1. list1 = [] list2 = [[[40], 70], [[[40], 70], 90]] def append_values(): amount = None if len(list1) == 0: amount = 70 list1.append([[40],amount]) else: amount = 90 list1.append([list1[-1],amount]) def alter_lists(): print('ori: ', list1) #Orginal list list1[1][0][1] = "alt" print('alt: ', list1) #Altered list print('\n') print('ori: ', list2) #Orginal list list2[1][0][1] = 'alt' print('alt: ', list2) #Altered list append_values() append_values() alter_lists()Output: ori: [[[40], 70], [[[40], 70], 90]] alt: [[[40], 'alt'], [[[40], 'alt'], 90]] ori: [[[40], 70], [[[40], 70], 90]] alt: [[[40], 70], [[[40], 'alt'], 90]] RE: Manipulating index value, what is wrong with this code? - perfringo - Feb-05-2020 There is nothing wrong, it's as it should be. In [1]: lst = [] In [2]: lst.append([1,2]) In [3]: lst Out[3]: [[1, 2]] In [4]: id(lst[0]) Out[4]: 4797778952 In [5]: lst.append(lst[0]) # append same item second time In [6]: lst Out[6]: [[1, 2], [1, 2]] In [7]: id(lst[1]) # both items refer to same object Out[7]: 4797778952 In [8]: lst[0].append(3) # changing the object In [9]: lst Out[9]: [[1, 2, 3], [1, 2, 3]] # changes both as the reference is to the same object In [10]: id(lst[0]) == id(lst[1]) Out[10]: TrueIf this behaviour is not desired you can append new object: In [11]: lst.append([1, 2, 3]) # append new list In [12]: lst Out[12]: [[1, 2, 3], [1, 2, 3], [1, 2, 3]] # not visually distinguishable from other items in list In [13]: id(lst[2]) Out[13]: 4796667592 # not same object (different id) In [14]: id(lst[0]) == id(lst[2]) Out[14]: False In [15]: lst[2].append(4) # appending to new item In [16]: lst Out[16]: [[1, 2, 3], [1, 2, 3], [1, 2, 3, 4]] # appends only to new object |