0

I have created a list of hashes as follows in python:

>>> hash_obj = [{}]*3

However, updating any one of the hashes in this list updates all elements:

>>> hash_obj[0]['a'] = True
>>> print(hash_obj)
[{'a': True}, {'a': True}, {'a': True}

Is there a clean 'pythonic' way to create a list of repeated independent elements? I also think the behaviour here is counterintuitive and should be changed, very interested to know why developers implemented as such.

Parsa
  • 3,054
  • 3
  • 19
  • 35
  • If you put the identical object multiple times in the same collection (or once in multiple collection), why would you expect a mutation on said object to only affect one reference to the object and not all of them? – user2390182 Sep 23 '19 at 08:21
  • I just wanted to initialise 9 independent hashes in a list without typing out `[{}, {}, {}, ... {}]`. Also the reverse of your question is equally true, why would anyone create multiple objects in the same list where each object is an eact duplicate of the others? There is no advantage to having a list of identical elements versus a list of just one of said element. – Parsa Sep 23 '19 at 09:17
  • 1
    This is more down to how the `*` operator is overloaded by `list`. The list **instance** that it is applied to cannot know how the objects inside it got instantiated and magically reapply that process. For specific reinstantiation, just use a comprehension: `[{} for _ in range(3)]` slightly more verbose, but the `a` expression in `[a for b in c]` is guaranteed to be evaluated every iteration. – user2390182 Sep 23 '19 at 09:24

0 Answers0