We can concatenate two arrays in python into a list with the to_list() function. The only catch here is the array must be of one dimension otherwise typecasting of the array into a list will become difficult. Here, we have to either use the revel() or flatten() function of numpy. It will convert a multidimensional numpy array in one dimension and then we can use the to_list() function. It will convert the NumPy array into a list data structure. So let’s start.
Concatenate two arrays of python into a list: Steps
Here to make the explanation for the conversion of two arrays into a list easy, we will take two samples numpy array. For giving the topic more diversity, We will take one numpy array as one dimensional and another one will be two dimensional.
import numpy as np arr1 = np.array([1, 2, 3, 4, 5]) arr2 = np.array([[11, 12] ,[13, 14, ]]) print(arr1.shape) print(arr2.shape)
Step 1: Check the shape & convert it into one dimensional –
If the shape of both arrays is not one-dimensional then we have to convert them into one-dimensional arrays.
As we can see that the shape of the first numpy array (arr1) is one-dimensional but the second numpy array arr2 is 2 dimensional hence we will convert the second Empire into a one-dimensional shape. Let’s see how to achieve the same.
This flatten() function will convert multi-dimensional array to single dimensional array.
Step 2: Concatenate two arrays of python into a final array-
Now we will concatenate both arrays. To concatenate them we will use concatenate(). Below is the full syntax with an example.
arr_final = np.concatenate((arr1, arr2))
Step 3: Conversion of the final array into list-
Here we will use the to_list() function for numpy array conversion to a list object. Below is the syntax for the same.
Here final_list is what we were looking for as the output. It is the list formed after the Concatenation of two arrays python into a list.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.