0

I'm trying to make an array of some objects (another array or dict), like:

a = {"authorName" : 0}
b = [a] * numOfAuthors     # numOfAuthors = 300, predefined

My objective is that each element in b should be a copy of a, such that they can be modified independently without affecting each other, but clearly the code shown will result in: modifications to any element in b will be reflected to all others due to the assignment. Hence I tried changing it to:

b = [copy.deepcopy(a)] * numOfAuthors

from this link. But it's still behaving in the old way. If I do:

b[0]["Ben"] = 12

then b will be a list of {"Ben": 12}. How should I resolve this?

Community
  • 1
  • 1
richards
  • 517
  • 9
  • 27
  • 2
    Multiplication doesn't make copies of the contents of the list, so `[] * ` produces a list with `` references to one object ``. – Martijn Pieters Jan 21 '17 at 17:00
  • `[copy.deepcopy(a)] * numOfAuthors` -> `[copy.deepcopy(a) for _ in xrange(numOfAuthors)]` – Allen Jan 21 '17 at 17:14

0 Answers0