How to Shallow Copy an Array in Python and Add Another Array to a List?

Estimated read time 2 min read

In Python, you can shallow copy an array using the copy method and add another array to a list using the append method. Here’s an example code that demonstrates both:

import numpy as np

# Create an array
arr1 = np.array([1, 2, 3, 4])

# Shallow copy the array
arr2 = arr1.copy()

# Add another array to a list
list1 = [arr1, arr2]
arr3 = np.array([5, 6, 7, 8])
list1.append(arr3)

# Print the result
print(list1)

In this example, we first create an array arr1 with some values. We then create a shallow copy of arr1 and store it in arr2 using the copy method.

Next, we create a list list1 containing arr1 and arr2, and we add another array arr3 to the list using the append method.

Note that a shallow copy of an array creates a new array object with a new memory address, but it still references the same data as the original array. This means that if you modify the data in the shallow copy, it will also affect the original array.

Also, when you add an array to a list using the append method, it creates a new reference to the same array object, so any changes to the array will affect the list and vice versa. If you want to create a new array object with a new memory address, you can use the copy method before adding it to the list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply