2

The code that I am working on is changing my temporary variables, and I can't figure out how to stop it. Essentially, this is the problem:

def example(array):
    temp = array
    for i in range whatever:
        #change array

I need to change array, but keep temp the same.

1
  • 1
    You usually only need the copy module if you need a generic copying function to copy objects independent of their type. Commented Jul 6, 2012 at 12:35

2 Answers 2

6

The line

temp = array

does not copy the contents of array – it simply binds another name to the same object. How to actually copy an object depends on the type of the object. For a NumPy array, you can do

temp = array.copy()

For a Python list, you can use the above line starting from Python 3.3; in eariler version, you can use

temp = array[:]

There are also the generic copying functions copy() and deepcopy() in the module copy.

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

2 Comments

I tried both of these options, and neither seems to work. temp continues to change.
Nevermind. I'm just an idiot and skipped over the 'deepcopy()' suggestion. It worked perfectly. A million, billion thanks.
1

temp = array only indicates that temp is another name for the contents of the array variable.

In general, if you want a copy, you can use the copy module and do:

import copy

temp = copy.copy(arr)  # or copy.deepcopy(arr), depending on the situation

Comments

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.