Create array from another array in Python (Copy array elements)
In this tutorial, you will learn how to create an array from another (existing) array in Python. In simpler words, you will learn to copy the array elements into another array.
You must be familiar with what an array is and its uses.
To recap, an array is a data structure that stores multiple elements (values) in a single variable.
Using Python NumPy library’s method-copy ()
Syntax:
array2=array1.copy()
On execution, the above statement returns a new array – array2, which contains exactly the same elements as array1.
Here,
array1 is the n-dimensional array to be copied.
array2 is the new array to be created to contain elements of array1.
The same is shown below:
import numpy as np array1=np.array([1,2,3]) print("array 1",array1) array2=array1.copy() print("array 2",array2)
array 1 [1 2 3] array 2 [1 2 3]
It is important to note that first, we are creating a new array instance. Then, we are copying the contents of the original array into the new one.
Thus, any changes you, later on, make to the first array will not be reflected in the copied array.
import numpy as np array1=np.array([1,2,3]) array2=array1.copy() array1[1]=7 print("array 1",array1) print("array 2",array2)
array 1 [1 7 3] array 2 [1 2 3]
Well, what happens if you use the assignment operator (=) to copy the array elements?
It not only copies the elements but also assigns them as equals. So, any changes made to array1 will automatically be reflected in array2 as shown.
import numpy as np array1=np.array([1,2,3]) array2=array1 array1[1]=7 print("array 1",array1) print("array 2",array2)
array 1 [1 7 3] array 2 [1 7 3]
In better words, you are not creating a new object, but in fact, creating a reference to the original object. For better understanding, observe the code below:
import numpy as np array1=np.array([1,2,3]) array2=array1 array1[1]=7 print(id(array1)) print("array 1",array1) print(id(array2)) print("array 2",array2)
1924624603936 array 1 [1 7 3] 1924624603936 array 2 [1 7 3]
If you have observed, when you were using the copy () method, you were creating a new array object and not just a reference instance for the original object.
Copying the array elements into a new array by looping through in Python
- Create a new array with the same length as that of the one to be copied
- Loop through the two arrays, copying the elements from the first and then assigning them to the second respectively.
Note:
Even in this case, you are copying the elements into another array. So, any changes made to array1 will not be reflected in array2.
import numpy as np array1=np.array([1,2,3]) print("array 1",array1) array2=[None]*len(array1) for i in range(0,len(array1)): array2[i]=array1[i] print("array 2",array2)
array 1 [1 2 3] array 2 [1, 2, 3]
To learn more about Python arrays, Python Array Module
Leave a Reply