Skip to content

Instantly share code, notes, and snippets.

@amitsaha
Created August 27, 2012 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitsaha/3487468 to your computer and use it in GitHub Desktop.
Save amitsaha/3487468 to your computer and use it in GitHub Desktop.
Array passing "by value" and "by reference" in Python
# Demo of passing an array
# such that the original array
# is:
# 1. Changed
# 2. Remains unchanged
# Python 3
import copy
from array import array
def func(arr):
print('Object Identifier: {0:d}'.format(id(arr)))
for i in range(0,len(arr)):
arr[i] = arr[i]**2
if __name__=='__main__':
print('\nOriginal array changes::\n')
arr=array('i',[1,2,3])
print(arr)
print('Object Identifier: {0:d}'.format(id(arr)))
# results in passing a reference to the
# the original array
func(arr)
print(arr)
# send a copy
print('\nOriginal array doesn\'t change::\n')
arr=array('i',[1,2,3])
print(arr)
print('Object Identifier: {0:d}'.format(id(arr)))
# Pass the copy of
# the original array
myarr = copy.copy(arr)
func(myarr)
print(arr)
Original array changes::
array('i', [1, 2, 3])
Object Identifier: 3075060736
Object Identifier: 3075060736
array('i', [1, 4, 9])
Original array doesn't change::
array('i', [1, 2, 3])
Object Identifier: 3075063072
Object Identifier: 3075060736
array('i', [1, 2, 3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment