0

I'll keep it short: I have a list of binary strings that, after being multiplied, show strange behaviour.

Here it goes.

binary_strings = [[0, 1, 1, 0], [1, 0, 1, 1]] * 4
for index, string in enumerate(binary_strings):
    if index == 0:
        string += [0]

expected result:

[[0, 1, 1, 0, 0],
 [1, 0, 1, 1],
 [0, 1, 1, 0],
 [1, 0, 1, 1],
 [0, 1, 1, 0],
 [1, 0, 1, 1]]

result achieved:

[[0, 1, 1, 0, 0],
 [1, 0, 1, 1],
 [0, 1, 1, 0, 0],
 [1, 0, 1, 1],
 [0, 1, 1, 0, 0],
 [1, 0, 1, 1]]

If binary_strings is not multiplied, then it works as expected. If insted of += operator I use string = string + [0], result is also 'correct'.

This is a problem that I have a solution to, but would really like to understand what is going on as it migth prevent future problems. It seems to be something related to the way python relates objects in memory. Other than that, I have no further understanting of might be going on.

Thanks!

edit: another issue here is that changing the operator changes the outcome to the corrected one, which is not something I have seen discussed. If it has, please link me that discussion. Thanks!

0 Answers0