Python - How To Append 2D Array in Python

ID : 470

viewed : 132

Tags : PythonPython Array

vote vote


In Python, we can have ND arrays. We can use the NumPy module to work with arrays in Python.

This tutorial demonstrates the different methods available to append values to a 2-D array in Python.

Use the append() Function to Append Values to a 2D Array in Python

In this case, we will use Lists in place of arrays. The list is one of the four built-in datatypes provided in Python and is very similar to arrays. NumPy arrays can be converted to a list first using the tolist() function.

The append() function is utilized to add an item to the specified list’s end. This function does not create a new list but modifies the original list.

The following code uses the append() function to append a 2D array in Python.

a = [[],[]] a[0].append([10, 20]) a[1].append([80,90]) print(a) 


[[[10, 20]], [[80, 90]]] 

A twoD list is created in the above code first, and then we add the required elements using the append() function. It adds the provided values to the end of the list.

We can convert the final result to a NumPy array using the numpy.array() function.

Use the numpy.append() Method to Append Values to a 2D Array in Python

The NumPy library deals with multiD arrays and provides functions to operate on the arrays given in the code smoothly.

We can utilize the numpy.array() function in the creation of an array. The NumPy module contains a function numpy.append() that is utilized to append the elements to the end of the given array.

The numpy.append() method has the following syntax.

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

It is important to note that if the axis value is not provided, then a multidimensional array flattens out, resulting in a 1D Array. Moreover, the values provided also need to be of a shape similar to the given array.

The following code uses the numpy.append() function to append a 2D array in Python.

import numpy as np arr5 = np.array([[10,20,30],[100, 200, 300]]) arr6 = np.array([[70, 80, 90],[310, 320, 330]]) newselect = np.append(arr5, arr6 , axis=1)     print(newselect) 


[[ 10  20  30  70  80  90]  [100 200 300 310 320 330]] 

  • Related HOW TO?