How to append a 2-dimensional array in Python?

Ways to append a 2-dimensional array in Python

There is no direct built-in support for Arrays in Python. However, we can make use of Lists instead when there is a need for a one-dimensional or a two-dimensional array. Moreover, the external NumPy library enables us to deal with n-dimensional arrays in Python.

To append a 2-dimensional array in Python:

  1. Using the append() function.
  2. Using the numpy.append() function.

Using the append() function.

The append() function is capable of adding a specified item at the very end of a given list. The work is done directly on the original list without the hassle of creating any fresh copies.

Consider the code below.

# Create an empty list
x = [[],[]]
# append something to the first index
x[0].append([40, 50, 60])
#append something to the second index
x[1].append([4,5,6])
print(x)
# Output: [[[40, 50, 60]], [[4, 5, 6]]]

The above code creates an empty two-dimensional array first by using lists. The

 Using the numpy.append() function.

The numpy.append() function carries out the same task as the append() function, but for NumPy arrays.

For the basic creation of an array in Python, the numpy.array() function can be utilized. The function, which is contained within the NumPy module makes it possible to append the elements at the end of the given NumPy Array.

A very peculiar and unskippable note about a NumPyarray is that if the axis value is not provided, it would lead to the flattening of the multi-dimensional array, and as a result, we would get a one-dimensional array.

Consider the below code.

# Import the NumPy module
import numpy as np
# Create two NumPy arrays and define their values.
x = np.array([[8,9,10],['hearts', 'hearts', 'hearts']])
y = np.array([[7, 2, 5],['spade', 'club', 'diamond']])
# Use the numpy.append() function to append an x with y
z = np.append(x, y , axis=1)    
print(z)
# Output(Line1): [['8' '9' '10' '7' '2' '5']
# Output(Line2):  ['hearts' 'hearts' 'hearts' 'spade' 'club' 'diamond']]

To Conclude

This tutorial provides a walkthrough and demonstrates all the various ways at one’s disposal to append a 2-dimensional array in Python. We can successfully carry out the process of appending a 2-dimensional array in the cases of both lists and `NumPy` arrays in Python.

Explore more from this category at Python NumPy Arrays. Alternatively, search and view other topics at All Tutorials.