Home > Software engineering >  Python 3 assigning list instance
Python 3 assigning list instance

Time:06-30

I have a small (I hope) problem with Python (3.8)

Let's say we have a list :

mylist=['item1','item2','item3']

Now, let's say I create a dict with a key:value pair:

mydict={'key1':mylist}

Then :

print(str(mydict))

Properly outputs :

{'key1':['item1','item2','item3']}

But, if I now append a value to mylist with :

mylist.append('item A')

I notice that :

print(str(mydict))

now outputs :

{'key1':['item1','item2','item3','item A']}

How can I avoid this? I want the list in mydict not to be updated... In other words, I want the mydict entry to contain the instance of mylist (before the append)...

CodePudding user response:

A simple solution would be to reassign the initial mylist to another variable (say mylist0), then use this for the dictionary assignment, so it does not update. This would work in a loop as well (if that is the intent) so long as you reassign mylist0 within the loop.

CodePudding user response:

Create a copy of the list with:

mydict={'key1':mylist.copy()}

This way the dictionary will contain a new, separate list of items.

  • Related