0

So, I just ran into some unexpected behavior regarding While Loops in Python.

Consider the following Code:

num = 0
array = [0, 1, 2]

while num < 5:
    newarray = array
    newarray[0] += 1
    print newarray
    print array
    num += 1

I expect newarray to be reset to array each iteration and array to stay the same. However in the print function they both change their values. I have already solved this problem with the copy module, but I'm left wondering, why is it behaving that way?

If you replace the array with an int it behaves as I would expect.

anon
  • 123
  • 5
  • 1
    https://docs.python.org/3/faq/programming.html#why-did-changing-list-y-also-change-list-x – CristiFati Jan 23 '19 at 00:21
  • was too focused on the while loop part to check for just lists, sorry! – anon Jan 23 '19 at 00:21
  • @anon your expectation is simply incorrect. Please read https://nedbatchelder.com/text/names.html `some_var = some_other_var` **never copies the object referenced by `some_other_var`**. Never. It *always* simply makes `some_var` reference the same object as `some_other_var` – juanpa.arrivillaga Jan 23 '19 at 00:30
  • Also note, that is not an array, that is a `list`. Although, again, *assignment regardless of the types of object involved* **never** copies. – juanpa.arrivillaga Jan 23 '19 at 00:31

0 Answers0