1

Here:

a = [{}] * 2
a[0]['x'] = 1
print a

will show a is [{'x': 1}, {'x': 1}], likely python just copy the reference, a[1] is referring to a[0].

And

a = [0] * 2
a[0] = 1
print a

will show a is [1, 0], a[0] and a[1] is different.

Could somebody explain it? Thank you.

smac89
  • 39,374
  • 15
  • 132
  • 179
superK
  • 3,932
  • 6
  • 30
  • 54

2 Answers2

2

The difference comes from how the elements of your list are defined. In the first case, you create a list of two dictionaries, but those dictionaries contain the same reference, i.e., they're pointing to the same memory space. When you do a[0]['x'] = 1 You're changing the data the dictionary is pointing to and since both dictionaries in your list are pointing to the same space, they both appear to update.

In the second case, you have a list of two numbers, both of which technically point to the same spot (where python has pre-allocated zero). When you do a[0] = 1, you're not changing the data in the space where the first element is pointing, you're resetting where that element is pointing. Specifically you're redirecting it to 1. That way only the first element updates, but the second is still pointing at 0.

zephyr
  • 2,182
  • 3
  • 29
  • 51
1

In the first example, the references in both positions of the list are pointing to the exact same dictionary. The correct way to do it is:

a = [{} for x in range(2)]

The second example is different:

a = [0] * 2

The number zero is copied across the list, but if you reassign the value on one of the positions that contain it, you'll simply copy a new number on the given index.

The key point is that in the first example the dictionary is a mutable object, whereas a number is not, and besides in the first example you performed an operation that mutated the dictionary, whereas in the second example you just reassigned the value in the list.

Óscar López
  • 232,561
  • 37
  • 312
  • 386