Python clone/copy array

Python cloning an array (list) using slice operator.

arr = ["v1", "v2", "v3", "v4", "v5"]
ref_arr = arr  ##ref to arr
ref_arr[0] = "new v1" ## will change in arr also

## This will create new copy
cloned_arr = arr[:]
cloned_arr[0] = "new v1 in cloned" ## will not change arr and ref_arr
print arr
print ref_arr
print cloned_arr
['new v1', 'v2', 'v3', 'v4', 'v5']
['new v1', 'v2', 'v3', 'v4', 'v5']
['new v1 in cloned', 'v2', 'v3', 'v4', 'v5']
Env: Python 2.7.6
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments