2

I have a simple function that is supposed to run down the diagonal of an array and turn all the values to 0.

def diagonal_zeros(dataset):
    zero = dataset[:]
    length = len(zero)
    for i in range(length):
        zero[i, i] = 0
    return zero

When I run this function on an array, it outputs the new, correct 'zero' array, but it also goes back and overwrites the original 'dataset.' I had thought that the line zero = dataset[:] would have prevented this.

I do not, however, get the same behavior with this function:

def seperate_conditions(dataset, first, last):
    dataset = dataset[first:last, :]
    return dataset

Which leaves the first dataset unchanged. I've been reading StackOverflow answers to related questions, but I cannot for the life of me figure this out. I'm working on a scientific analysis pipeline so I really want to be able to refer back to the matrices at every step.

Thanks

1
  • You are using numpy, I presume. numpy slicing returns a view, not a copy. Commented Nov 17, 2017 at 17:11

1 Answer 1

6

Arguments in python are passed by assignment (thanks to @juanpa.arrivillaga for the correction) and not by value. This means that generally the function does not recieve a copy of the argument, but a "pointer" to the argument itself. If you alter the object referenced by the argument in the function, you are modifying the same object outside. Here's a page with some more information.

A possibility is to use the copy module inside your function, to create a copy of the dataset.

As an example, for your code:

import copy
myDataset = [[1,2,3],[2,3,4],[3,4,5]]

def diagonal_zeros(dataset):
    zero = copy.deepcopy(dataset)
    length = len(zero)
    for i in range(length):
        zero[i][i] = 0
    return zero

result = diagonal_zeros(myDataset)
print(result)     #[[0, 2, 3], [2, 0, 4], [3, 4, 0]]
print(myDataset)  #[[1, 2, 3], [2, 3, 4], [3, 4, 5]]

This article helped me a lot with this concept.

Sign up to request clarification or add additional context in comments.

2 Comments

@juanpa.arrivillaga you are right, I edited the comment for clarity.
the same applies to VBS (and probably many other languages) as well, I found this while searching for the same issue for VB and this explains the issue perfectly. You could possibly point out that it applies to other languages than just python

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.