0

I have a problem in my code.
I am trying to make a assambler for my own assambly language.
And in a for loop that reads the code and replaces a instruction the for loop does not end.

Here is the piece of code:

asm = ["DW,1,2,4,5"] #example
i = 0
b1 = asm #copy of asm
for item in asm: #loop trough asm
    if item.split(",")[0] == "DW": #check if the item is the instruction DW
        plist = item.split(",")[1:] #create a list of the item
        for line in plist: #go trough the parameters of DW and insert them in to b1
            b1.insert(i,"DB," + line)
            i += 1
asm = b1

The code does not delete the DW instruction yet.

The contents of list asm after i do a keyboard interupt:

>>> asm
Squeezed text (8781 lines).

Somehow it appends to list asm. Any help would be appreciated.

pizeck
  • 1
  • 1
  • 2
    Your line: `b1 = asm #copy of asm` does not make a copy. Mandatory link to [Ned Batchelder](https://nedbatchelder.com/text/names.html) – quamrana Jun 09 '21 at 18:19
  • 2
    Does this answer your question? [List changes unexpectedly after assignment. Why is this and how can I prevent it?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it) – enzo Jun 09 '21 at 18:20
  • thanks it worked with asm.copy() – pizeck Jun 09 '21 at 18:25

1 Answers1

2

When you did b1 = asm in line 3, Python is essentially creating a variable named b1 that points to the same object in memory as asm. This is a known behavior where lists created this way are referenced to the same object in memory. This means when you write to b1, asm is also being updated.

What you need is b1 = asm.copy() on line 3 and asm = b1.copy() at the end to make sure the objects are kept separate.

xyzjayne
  • 1,331
  • 9
  • 25