0

I wanted to insert a new item in my list.However, because i wanted to keep my original list intact, i equaled my original list to another string letter. However, when i insest to the "s" list, this new element, it is inserted to all lists even though no such operation is performed!

Why? I am missing something: (Pycharm with Python 2.3).

l_max=[1,2,3]
a=l_max
b=a
c=b
s=c
s.insert(0, 0)
Estatistics
  • 874
  • 9
  • 24
  • thanks you for notifying me about these posts while i did search. probably i did not used the right search terms as newbie! I did not used words like "update" or "iterate". Both posts used these words :) – Estatistics Mar 15 '16 at 17:44

1 Answers1

1

Rather than assigning a list to another list b = a, you want to set it to a copy: b = a[:]

l_max=[1,2,3]
a=l_max # a points to l_max
b=a     # b points to a
c=b     # so on
s=c     # so forth
s.insert(0, 0) # insert into the only list, which all variable point to 

you want:

l_max=[1,2,3]
a=l_max[:] # create copy
b=a[:]
c=b[:]
s=c[:]
s.insert(0, 0) # insert only into s
Will
  • 4,299
  • 5
  • 32
  • 50
  • I solved this problem... BUT why it is inserted recursively, into all other lists even when this is not declared explicity? – Estatistics Mar 03 '16 at 19:32
  • 1
    The way you were doing it originally is not creating new lists, only new references to the first list. There is only one list (`l_max`), and all subsequent lists will refer to the same spot in memory, where the first list was. So, inserting into any of these references will insert into the only list. By using `[:]`, you create a new copy of the list in memory, which can then be inserted into without affecting the other lists. In short: your way has only one list, `[:]` creates copies. You can read more about pointers in C to get an idea of how this works. – Will Mar 03 '16 at 19:40
  • 1
    http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python?lq=1 Here is a good reference for this issue in python, and here's a good one for pointers and references: http://www.cplusplus.com/doc/tutorial/pointers/ – Will Mar 03 '16 at 19:42