0

This is python 2.7.10.

I am giving one example of what I am asking. I am swapping the first and second element of an array via a function.

#!/usr/bin/python
def change(array):
    array2 = array
    array2[0], array2[1] = array2[1], array2[0]
    return array2


a = [100, 200, 300]
print "Original array: "
print a #[100, 200, 300]
print "Feeding to some function"
b = change(a)
print "Original array becomes: "
print a #[200, 100, 300] <- Unexpected
print "Result of my function: "
print b #[200, 100, 300]

I thought the function should not alter the value/status of feed-in parameters. In other words, array a should be still [100, 200, 300] after running through function change.

My question is following:

  • Am I doing wrong? I know how to use __main__ related.
  • Could you guys walk me through "wired" behavior? Is there any term/page to describe such a behavior of python language?

To me, python works like:

Input -> function -> Output + Input_altered

But I assumed it should work like:

Input -> function -> Output + Input

Puriney
  • 2,417
  • 3
  • 20
  • 25

1 Answers1

0

If you don't want the original object to be changed then use change(a[:]) or change(a.copy()).

cdonts
  • 9,304
  • 4
  • 46
  • 72
  • Thank you for answering. I am trying to understand what is going on with python. For example in `R`language. `mychange <- function(a){ temp = a[1]; a[1] = a[2]; a[2]=temp; return(a)}`. Feed an array to function `mychange`, input will be not changed at all. For me, python function is not isolated from input, unless do something as you pointed out here. Did I got the point? – Puriney Oct 25 '15 at 17:26
  • @Puriney: Jack's answer at the [dupe target](http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python) explains why this happens in Python. If you want to read more about this, please see [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html) by SO veteran Ned Batchelder. – PM 2Ring Oct 26 '15 at 07:26