numpy.append() in Python

What is numpy.append()?

The numpy.append() function in Python is used to add elements to the end of a NumPy array while returning a new array. Since NumPy arrays have a fixed size, they cannot be modified in place, so numpy.append() creates a copy of the original array with the new values appended.

Working of numpy.append() Method

  • The function takes an existing NumPy array and adds specified values to it.
  • If the axis parameter is not specified (axis=None), both the original array and values are flattened into a 1D array before appending.
  • If an axis is provided, the function appends values along the specified dimension.
  • The original array remains unchanged, as a new array is created and returned.

This function is particularly useful when working with numerical data where appending values dynamically is required, such as in data preprocessing, mathematical computations, or scientific research.

Why use numpy.append()?

  • Handles array extension efficiently – Unlike Python lists, NumPy arrays require explicit resizing, which numpy.append() manages smoothly.
  • Maintains numerical data types – It ensures that all elements remain in a consistent data type, preventing type mismatches.
  • Works with multi-dimensional arrays – You can append values along a specific axis when working with 2D or 3D arrays.

Syntax of numpy.append()

To use numpy.append(), the function follows this syntax:

python
1
numpy.append(arr, values, axis=None)

Breakdown of the Syntax:

  • arr → The input array to which new values will be appended.
  • values → The values to append; must match the shape of the existing array.
  • axis (optional) → The axis along which values should be appended. If None, the array is flattened before appending.

Parameters of numpy.append()

  • arr: The original NumPy array to which elements will be appended.
  • values: The new elements that will be added to the array. It can be a single value, list, or another NumPy array.
  • axis: The axis along which values should be appended. If None, the function appends values to a flattened version of the array.

Return Type of numpy.append()

The function returns a new NumPy array that includes the appended values. The original array remains unchanged because NumPy arrays have a fixed size, meaning modifications require creating a new instance.

Example 1: NumPy Append to an Empty Array

Problem Statement

Suppose you need to create an array dynamically by appending elements one by one. Since NumPy arrays do not support dynamic resizing, you start with an empty array and append new values.

Steps to Solve:

  • Initialize an empty NumPy array.
  • Use numpy.append() to add elements.
  • Observe that a new array is created each time an element is added.

Code Example:

python
1
2
3
4
5
6
7
8
9
10
import numpy as np

# Start with an empty NumPy array
arr = np.array([])

# Append values one by one
arr = np.append(arr, 10)
arr = np.append(arr, [20, 30, 40])

print(arr)

Explanation:

  • We create an empty NumPy array using np.array([]).
  • The np.append() function adds elements, one at a time or as a list.
  • A new array is returned each time append() is used, which we assign back to arr.
  • The final array contains [10, 20, 30, 40].

Example 2: NumPy Append in Place

Problem Statement

Appending values directly to an existing NumPy array without reassigning a new array is not possible, as NumPy arrays have a fixed size. However, you can reassign the result to the same variable to simulate in-place modification.

Steps to Solve:

  • Create an initial NumPy array.
  • Append new values using numpy.append().
  • Assign the result back to the original variable.

Code Example:

python
1
2
3
4
5
6
7
8
9
import numpy as np

# Create an initial array
arr = np.array([1, 2, 3])

# Append new elements and assign back to 'arr'
arr = np.append(arr, [4, 5, 6])

print(arr)

Explanation:

  • The original array [1, 2, 3] is created.
  • np.append() adds [4, 5, 6], returning a new array [1, 2, 3, 4, 5, 6].
  • The new array is reassigned to arr, as NumPy arrays do not support in-place appending.

Alternatives for numpy.append()

While numpy.append() is useful, it is not always the most efficient method. Below are some alternatives:

1. Using numpy.concatenate()

  • If you are merging two NumPy arrays, numpy.concatenate() is often faster.
  • Unlike numpy.append(), it requires the arrays to have the same shape.

Example:

python
1
np.concatenate((arr1, arr2), axis=0)

2. Using numpy.insert()

  • If you need to add values at a specific index, numpy.insert() is a better option.
  • Unlike numpy.append(), it allows inserting values at any position, not just at the end.

Example:

python
1
np.insert(arr, index=2, values=50)

3. Using Python Lists (For Dynamic Resizing)

  • If performance is a concern, Python lists may be better for frequent appends, as they do not require reallocation.
  • Once the list is complete, you can convert it to a NumPy array.

Example:

python
1
2
3
arr_list = []
arr_list.append(10)
np.array(arr_list)

Key Takeaways

  • numpy.append() adds elements to the end of a NumPy array, returning a new array.
  • Original arrays remain unchanged because NumPy arrays have a fixed size.
    It works with 1D, 2D, and multi-dimensional arrays, appending along a specified axis if needed.
  • Using numpy.append() in loops is inefficient; alternatives like numpy.concatenate() or Python lists should be used for performance optimization.
  • There is no in-place appending in NumPy, so reassignment is required.

Conclusion

The numpy.append() function is extremely useful for adding values dynamically, but it should be used carefully due to its memory limitations. If you frequently append data, consider using lists first and converting to NumPy later or optimizing with alternatives like numpy.concatenate().

Frequently Asked Questions