0

Main problem

why the values are getting updated for every key ??

code

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's this happening and the possible solutions? That would be great if you can attach the related python documentation!!

1 Answers1

3

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. This module provides generic shallow and deep copy operations.

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.

Reference:

arsho
  • 11,915
  • 8
  • 45
  • 63
  • can you please help me understand why's this happening? Also, that would be great if you can attach the related python documentation!! – Shambhav Agrawal Jul 17 '21 at 16:41
  • 1
    @ShambhavAgrawal, here https://docs.python.org/3/library/copy.html –  Jul 17 '21 at 16:41
  • 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