-1

I would like to fill a dict with lists. But it seems like the dict keeps updating the values i pass in. I am currently doing something like this:

Dict=dict()
lst = list()
for i in range(10):
    lst.append(i)
    Dict[f'{i}']=lst
    

and would like to obtain Dict={'0': [0], 1: [1,2], ... }

but I get Dict={'0': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], '1': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], ...}

Is there a nice way to get around this?

Thanks for your help.

M. St.
  • 63
  • 6

1 Answers1

0

Dict[f'{i}']=lst inserts the exact same list object over and over again, because assignment generally doesn't copy objects. lst.append(i) modifies that one list object. So your dictionary ends up containing lots of pointers to the same list.

To insert a different object each time, copy the current list:

Dict[f'{i}']=lst.copy()
# or Dict[str(i)] = lst.copy()
ForceBru
  • 43,482
  • 10
  • 63
  • 98