2

I don't understand why the following happens. Python 2.7.2

parinfo = [{'limited':[0,0], 'limits':[0.,0.]}] * 3 
parinfo[2]['limited'][0] = 1
parinfo[2]['limited'][0] = 1

parinfo 
[{'limited': [1, 0], 'limits': [0.0, 0.0]},
{'limited': [1, 0], 'limits': [0.0, 0.0]},
{'limited': [1, 0], 'limits': [0.0, 0.0]}]
falsetru
  • 357,413
  • 63
  • 732
  • 636
Tom
  • 223
  • 1
  • 2
  • 11

3 Answers3

2
parinfo = [{'limited':[0,0], 'limits':[0.,0.]}] * 3 

Above line, instead of making 3 different dictionary objects, it creates one; all items in the list reference the same dictionary.

You need to do this way to create 3 separated dictionaries:

parinfo = [{'limited':[0,0], 'limits':[0.,0.]} for i in range(3)]
falsetru
  • 357,413
  • 63
  • 732
  • 636
2

Your question can be broken down into a few parts.

First, you are multiplying a list, which leverages the __mul__() magic method.

s.__mul__(n) -> results in s * n--repeated concatenation.

 >>> a = [1,2,3]
 >>> a * 3
 [1, 2, 3, 1, 2, 3, 1, 2, 3]

Furthermore, trying to initialize a list of lists will result in a list referencing three inner list, which is probably not what you want.

>>> a = [[]]
>>> a * 3
[[], [], []]

Second, you have created a key-value pair where the value is a list.

"limited" is the key to a list with three elements [1,2,3]

>>> dicty = {'limited': [1, 2, 3]}
>>> dicty['limited']
[1, 2, 3]

Third, you are essentially updating the 0th element in the list.

>>> dicty['l'][0] = 100
>>> dicty
{'l': [100, 2, 3]}
aidanmelen
  • 6,194
  • 1
  • 23
  • 24
-1
parinfo = [{'limited':[0,0], 'limits':[0.,0.]}] * 3 

This code creates a shallow copy instead of deep copy.

  • No not even a shallow copy. Just 3 references to the same dictionary object. See this [link](https://docs.python.org/2/library/copy.html) for an explanation about shallow copies (and deep copies as well). – Elmex80s Feb 20 '17 at 01:15