NumPy append()

The append() method adds the values at the end of a NumPy array.


append() Syntax

The syntax of append() is:

numpy.append(array, values, axis)

append() Arguments

The append() method takes three arguments:

  • array - original array
  • values - the array to be appended at the end of the original array
  • axis - the axis along which the values are appended

Note: If axis is None, the array is flattened and appended.


append() Return Value

The append() method returns a copy of the array with values appended.


Example 1: Append an Array

Output

[0 1 2 3 4 5 6 7]

Example 2: Append Array Along Different Axes

We can pass axis as the third argument to the append() method. The axis argument determines the dimension at which a new array needs to be appended (in the case of multidimensional arrays).

Output

Along axis 0 : 
[[0 1]
 [2 3]
 [4 5]
 [6 7]]

Along axis 1 : 
 [[0 1 4 5]
 [2 3 6 7]]

After flattening : 
 [0 1 2 3 4 5 6 7]

Example 3: Append Arrays of Different Dimensions

The append() method can append arrays of different dimensions. However, the similar method concatenate() can't.

Let's see an example.

Output

[1 2 3 4 5 6 7]
ValueError: all the input arrays must have the same number of dimensions 

Note: numpy.append() is more flexible than np.concatenate() as it can append a scalar or a 1D array to a higher-dimensional array. However, when dealing with arrays of the same shape, np.concatenate() is more memory efficient.