0

Why are the values getting updated for every key?

d = {0: [0], 1: [0, 1]}
for i in range(2, 4):
    d[i] = d[i - 1]
    d[i].append(i)
print(d)

Output:

{0: [0], 1: [0, 1, 2, 3], 2: [0, 1, 2, 3], 3: [0, 1, 2, 3]}

I want it like this in the output:

{0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]}

Can someone please help me understand why this is happening and the possible solutions? It would be great if you could attach the related Python documentation!

wjandrea
  • 28,235
  • 9
  • 60
  • 81

1 Answers1

4

Assigning a list will copy the elements by reference. Copy the values of the list using .copy() method.

From Python documentation:

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.

d = {0: [0], 1: [0, 1]}
for i in range(2, 4):
    d[i] = d[i - 1].copy()
    d[i].append(i)
print(d)

Output:

{0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]}

Explanation:

When we use d[i] = d[i-1] in d[i] stores the reference of the list stored in d[i-1]. Then when we are updating d[i] with the d[i].append(i) it updates the list of d[i-1] index too.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
arshovon
  • 13,270
  • 9
  • 51
  • 69
  • Thank you so much! but I wish to know what's wrong in my code "d[i] = d[i-1]" why it's updating everywhere ?? – Shambhav Agrawal Jul 17 '21 at 16:44
  • @ShambhavAgrawal it's because you're appending values to the same reference inside the loop. You can python's `id(obj)` (gives hash-value of obj) to check the reference of an object. – Rohit Babu Jul 17 '21 at 16:52