Python Practice › NumPy Programs › Program 84

Copy an array

EasyNumPy Programs · 84 of 100

Write a NumPy program to copy data from one array to another.

Advertisement
Output
[ 1 77  3] [99  2  3]

Approach

  1. copy() creates independent data; a slice is only a view.

Solution

Python
import numpy as npa = np.array([1, 2, 3])b = a.copy()view = a[:]b[0] = 99view[1] = 77print(a, b)
Output
[ 1 77  3] [99  2  3]

Line by line

Lines 5-7

Changing the copy leaves a alone, but changing the view changes a.

Learn the concept

New to this topic? Read the lesson, then come back.

More numpy programs

← All 100 NumPy Programs

Leave a Comment