Array passing "by value" and "by reference" in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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