0

Have you ever faced this behavior in assigning values to two (or more) different dict variables using the same list of values?

m1={}
m2={}
token=['a','b','c']
m1['12345']=token
m2['4422']=token
#both dict variables with different keys have the same list
token=['d','e','f']
m2['4422'].extend(token)
#m2['4422'] has the following values ['a','b','c''d','e','f'] as expected
#however m1 has the same values!!!
m1
#['a','b','c''d','e','f']

This question is different from a previous one (made by Lior) since it has some kind of a complicate indirection. I guess the answers of the prevuious question can help to understand this problem, but I think this one is a little bit more tricky.

D. Duarte
  • 1
  • 1
  • 1
    both dicts refer to the exact same object, so when you mutate that single object, it shows. – acushner Jun 22 '17 at 16:44
  • both `m1` and `m2` have a reference to the exact same list object in memory. – Christian Dean Jun 22 '17 at 16:44
  • 3
    This occurs even when not using dicts. Simpler example: `token = [1,2,3]; a = token; a.extend([4,5,6]); print(token)` – Kevin Jun 22 '17 at 16:44
  • it's because is refering the same object – Juan Diego Garcia Jun 22 '17 at 16:45
  • 1
    Unless you specifically tell Python to make a copy, assigning a mutable value to multiple variables which only make reference copies to the object, and not copies of the actual object itself. – Christian Dean Jun 22 '17 at 16:46
  • 2
    Yes. You have faced this all the time. It is how Python variables *always work*. However, this is a very common misunderstanding of how Python works, which is actually quite simple at the end of the day. Check out Ned Batchelder's [Facts and Myths about Python names and values](https://nedbatchelder.com/text/names.html). It's probably the best explanation that covers many common stumbling blocks. – juanpa.arrivillaga Jun 22 '17 at 16:49
  • Ok, now I got it. I have to create two diferent variables to feed the two dicts. – D. Duarte Jun 22 '17 at 19:28
  • Well, I have just to do `m2['4422']=token.copy()` and `m1['12345']=token.copy()`. – D. Duarte Jun 23 '17 at 06:39

0 Answers0