-2

I have this list of lists:

lst = [[1],[2],[3],[4]]  

And I want to move the i+1 element to the [0] index, like this:

[[2],[1],[3],[4]] / [[3],[1],[2],[4]] / [[4],[1],[2],[3]]    

This is my code:

lst = [[1],[2],[3],[4]]

a = []  
count =0
for i in range(1,5)  :
     
    temporary = lst
    
    lst.insert(0,lst[i])
    del lst[i+1]
    a.append(lst)
    print(lst,temporary)
    break
    

I see that the temporary variable doesn't store the initial values of lst. I assign the values of lst variable to temp variable before I make changes on the lst, hence I expect the temp variable to hold the initial values of lst, and not the changed values of lst. Where is my mistake?

Thanks

  • 4
    Mandatory link to [Ned Batchelder](https://nedbatchelder.com/text/names.html) – quamrana May 14 '22 at 19:55
  • 2
    All variables in python are references. All your code does there is to take a copy of the reference. Now you have two references to the same underlying `list`. Did you mean: `temporary = lst[:]`? – quamrana May 14 '22 at 19:56
  • 1
    A shortcut to *copying* a list would be `temporary = lst[:]`. This breaks the reference and creates a new list object in a new memory address. – S3DEV May 14 '22 at 19:58
  • 1
    Does this answer your question? [How do I clone a list so that it doesn't change unexpectedly after assignment?](https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment) – ddejohn May 14 '22 at 20:02
  • 3
    Side note, it is my opinion that using `[:]` to copy objects is bad practice. Use the more explicit `lst.copy()`. – ddejohn May 14 '22 at 20:03

0 Answers0