-3

I would like to replace a value in a specific index with specific value retrieved from excel. I'm getting my whole array being replace with the last value retrieved.

details= [[""] * 2 ] * 2
details_index=3
for count1 in range(len(details)-1):
    details[count1][0] = sheet.cell(row=count1+2, column=details_index).value

the output always return

[['0009', ''], ['0009', ''], ['0009', ''], ['0009', ''], ['0009', ''], ['0009', ''], ['0009', ''], ['0009', ''], ['0009', ''], ['0009', '']]

any idea what did the loop did wrong?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • You have a list of other lists that point to the same data. Use `details=[ ["" for column in range(2)] for row in range(2)]` instead. – Patrick Artner Mar 03 '19 at 15:17
  • See [How to clone or copy a list](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) how to solve it... – Patrick Artner Mar 03 '19 at 15:20

1 Answers1

0

When you multiply arrays you are referring to the pointer of the array and not making a copy.

[[""]*2]*2 is making [["",""]*["",""]]

but actually you only have ["",""] in memory. Therefore, if You change one of those you change all of them.

That is, if you take array[0][0] = ["9","0"] you take the location in memory and say ["",""] is now ["9", "0"] and so array = [["9","0"],["9","0"]].

One way to solve this is by using deepcopy which you can use by import deepcopy from copy

I think that is what you are asking.

Aviv Moshe Albeg
  • 131
  • 2
  • 10