-1

So I'm having A VERY STRANGE scenario, I've simplified the code, but having the SAME issues.

def write_to_bf_of_lpr(bf_source, bf_destination, lpr_index, start, length):
    for x in range(length):
        bf_destination[lpr_index][start + x] = bf_source[start + x]

source = ['a','b','c','d','e']

destination = [[0]*5]*3
dets2=[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

for x in range(1):
    write_to_bf_of_lpr(bf_source=source,bf_destination=dets2,lpr_index=x,start=1,length=2)

for x in range(1):
    write_to_bf_of_lpr(bf_source=source,bf_destination=destination,lpr_index=x,start=1,length=2)

this code is quite simple to understand, what I wish to do is only change specific array each time (or iteration).

Now: when I write in shorented version: destination = [[0]*5]*3 it is changing ALL the arrays within SINGLE iteration.

When I write in the LONG version (which is not preferable ) I get the CORRECT version.

You can see that dest2 is the correct, while destination is the wrong answer.

The funny thing is, that I simply COPIED the values from the short version... and there's different result...

Is it Pycharm bug, python, or am i missing something? please see screenshot of the output

enter image description here

Hemerson Tacon
  • 2,419
  • 1
  • 16
  • 28
Danny Kaminski
  • 191
  • 2
  • 15

1 Answers1

0

That's because when you define an array the way you have, you're basically creating copies of the reference which points to [0]*5 which means if you change one, they all change. You can do what you want in you're using numpy, this way when you change one index, only that index changes.

import numpy as np

destination = np.zeros((3, 5))

You can also do it without numpy as follows:

destination = [[0] * 5 for _ in range(3)]

ninesalt
  • 4,054
  • 5
  • 35
  • 75