I want to alter the values in my 2D list keyed within a dictionary. My code is altering all the values in my dictionary which is not intended.
cache_memory = {}
zero_list = ["0"] * 2 ["00"] * 5
empty_lists = []
# append zero_lists to empty_list to make a 2D LIST
for count in range(2):
empty_lists.append(zero_list)
# store 2D lists with keys
for index in range(2):
cache_memory[index] = empty_lists
cache_memory[0][0][0] = "1"
print(cache_memory)
Output is:
{0: [['1', '0', '00', '00', '00', '00', '00'], ['1', '0', '00', '00', '00', '00', '00']], 1: [['1', '0', '00', '00', '00', '00', '00'], ['1', '0', '00', '00', '00', '00', '00']]}
I want it to be:
{0: [['1', '0', '00', '00', '00', '00', '00'], ['0', '0', '00', '00', '00', '00', '00']], 1: [['0', '0', '00', '00', '00', '00', '00'], ['0', '0', '00', '00', '00', '00', '00']]}
Is there a way to achieve this in python or should I try a different workaround?
CodePudding user response:
In the following lines of your code
for count in range(2):
empty_lists.append(zero_list)
# store 2D lists with keys
for index in range(2):
cache_memory[index] = empty_lists
You are creating a shallow copy of the list which is nothing but a reference to the list. When you make changes in the copy, the same changes are reflected in the original list. That's why all the lists in your dictionary 'cache_memory' are references of the same list and modifying the element in one list modifies the list for all the references. To get your favourable output you need to create and store the deep copies of the list which can be achieved using copy module available in python. So you need to modify your code as:
import copy #importing copy module
cache_memory = {}
zero_list = ["0"] * 2 ["00"] * 5
empty_lists = []
# append zero_lists to empty_list to make a 2D LIST
for count in range(2):
empty_lists.append(copy.deepcopy(zero_list))
# store 2D lists with keys
for index in range(2):
cache_memory[index] = copy.deepcopy(empty_lists)
cache_memory[0][0][0] = "1"
print(cache_memory)
You can learn more about shallow copies and deep copies in this article Shallow vs deep copies in Python
CodePudding user response:
When you just say cache_memory[index] = empty_lists
, Python will take that as cache_memory[index]
and empty_lists
is one object. If you want to set cache_memory[index]
to a copy of empty_lists
, then you can either put .copy()
after empty_lists
in that line or [:]
. Both of these get a copy of empty_lists
instead of taking them both as one object.
If you want to explore this more, just use the following code snippet.
my_list = [1,2,3]
new_list = my_list
print('Prev my_list:',my_list)
print('Prev new_list:',new_list)
my_list.append(4)
print('New my_list:',my_list)
print('New new_list:',new_list) # As you can see new_list also gets updated