0

Is there any way i can pass in only the values of a list to a dictionary and not the reference of the list?

*my_list = [1, 2, 3]
my_dict = {"list": my_list}
print(my_dict["list"])
my_list.pop()
print(my_dict["list"])*

currently the output is: [1, 2, 3] [1, 2]

i want it to be: [1, 2, 3] [1, 2, 3]

Yajola
  • 5
  • 2

2 Answers2

0

You should create a new list with your original list's values in the dictionary so that it won't be mutated when you pop from my_list.

my_dict = {"list": [item for item in my_list]}
julia
  • 153
  • 1
  • 10
0

Create a copy of the list before adding it to the dict:

my_dict = {'list': list(my_list)}

What's happening is that my_dict['list'] is referring to the same value as my_list rather than a copy of it, i.e. sharing the data. Since .pop() destructively modifies the list, the element is lost in the variable as well.

See https://stackoverflow.com/a/2612815/10973209 for an overview of ways to copy a list and https://stackoverflow.com/a/430958/10973209 for an explanation of pass-by-reference vs pass-by-value in general.

ROpdebee
  • 249
  • 1
  • 7