-1

So bascially I want to have one array(result) to which I add sum of the second array (array) but when I try to add to result sum of array it adds to array what should be added to result

def some_function(signature, n):

    array = result = signature
    count = 1

    while count <= n:
            print(array)       # prints [1, 1, 1]

            result.append(sum(array))        # Here i don't get it why result.append modifies array.
                                                                     # Without result.append everything works fine
            print(array)       # prints [1, 1, 1, 3]

            array.append(sum(array))    

            print(array)       # prints [1, 1, 1, 3, 6]

        del array[0]

        count += 1

    return result

print(some_function([1, 1, 1], 10))
Nick is tired
  • 6,860
  • 20
  • 39
  • 51
mackotron
  • 1
  • 1
  • Because `array` and `results` both point to the same array. `signature` will also change with them. – 9769953 Jun 22 '21 at 12:28

1 Answers1

-1

array = result = signature doesn't copy anything. All three variables point to one and the same list because assignment doesn't copy.

Because they point the the same list, result.append(sum(array)) is exactly the same as array.append(sum(array)), or result.append(sum(signature)), or signature.append(sum(result)) - it's all the same.

You can copy lists manually:

array = signature.copy()
result = signature.copy()
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • Ye i figured it out couple minutes ago but i haven't known why till now. Thanks for making it clear I did array = [x for x in signature] and result = [x for x in signature] and it worked – mackotron Jun 22 '21 at 12:39