Copying Arrays in Python: Methods and Techniques

Learn how to copy arrays in Python to create duplicates with all the original elements. Explore methods like the assignment operator (=) and deepcopy(). This guide explains Python's array module and how it compares to arrays in other languages.


Sample Image

Python - Copy Arrays

Copying an array in Python means creating a new array that contains all the elements of the original array. This can be done using the assignment operator (=) and deepcopy() method.

Python's built-in sequence types like list, tuple, and string are indexed collections of items. Unlike arrays in C/C++, Java, etc., they are not homogenous. Python's array module helps create objects similar to Java-like arrays.

Python arrays can be of string, integer, or float type. The array class constructor is used as follows:

Syntax

import array
obj = array.array(typecode[, initializer])

Where the typecode may be a character constant representing the data type.

Copy Arrays Using Assignment Operator

Using the assignment operator (=) to copy an array doesn't create a new array in memory. Instead, it creates a new reference to the same array.

Example

import array as arr
a = arr.array('i', [110, 220, 330, 440, 550])
b = a
print("Copied array:", b)
print(id(a), id(b))
Output

Copied array: array('i', [110, 220, 330, 440, 550])
134485392383792 134485392383792

The same id confirms that the assignment doesn't create a copy. Changes in a will reflect in b too.

Example

a[2] = 10
print(a, b)
Output

array('i', [110, 220, 10, 440, 550]) array('i', [110, 220, 10, 440, 550])

Copy Arrays Using Deep Copy

To create a physical copy of an array, use the copy module and deepcopy() function. A deep copy constructs a new compound object and recursively inserts copies of the objects found in the original.

Example

import array as arr
import copy
a = arr.array('i', [110, 220, 330, 440, 550])
b = copy.deepcopy(a)
print("Copied array:", b)
print(id(a), id(b))
Output

Copied array: array('i', [110, 220, 330, 440, 550])
2771967069936 2771967068976

This proves that a new object b is created, which is an actual copy of a. Changes in a won't affect b.

Example

a[2] = 10
print(a, b)
Output

array('i', [110, 220, 10, 440, 550]) array('i', [110, 220, 330, 440, 550])