A little tip when working with arrays in Python.

This is a thing I learned the hard way! When you have defined an array, and pass it as an argument to a function or assign another variable the array, it will be passed BY REFERENCE, not BY VALUE. Quick example:

>>> a=[1,2]
>>> b=a
>>> a
[1, 2] 
>>> b
[1, 2]
>>>
b.append(3)
>>> a
[1, 2, 3]

This is most likely NOT the behavior you want or expect.

What you need to do, is to copy the array, like this:

# python
>>> a=[1,2]
>>> b=a[:]
>>> a
[1, 2]
>>> b
[1, 2]
>>> b.append(3)
>>> a
[1, 2]
>>> b
[1, 2, 3]

So, use the second method if you want a copy of the array. Likewise when passing it as an argument to a function:

my_array=[1,2,3,4]
some_function(my_array[:])  # some_function receives a copy of the array

That is all. :-)


Written by Jannich Brendle fre 24 februar 2012 In Programming

tags: quick tips

Related posts

social