Create Array of Arrays in Python

Create array of arrays in Python

Use numpy.array() Function

To create an array of the arrays in Python:

  • Use the np.array() function to create a numpy.ndarray type array of the arrays.

The Python library NumPy scientifically computes advanced numerical work. It is a language extension that adds support for large, multi-dimensional arrays and matrices in the Python language.

The numpy library provides multi-dimensional array objects that work like arrays in C but with a Python interface. It can therefore act as a bridge between Python and the low-level languages used for scientific computing.

We used the np.array() function to create three arrays: array1, array2, and array3. After we finished generating the arrays, we used the np.array() function to create an arrays of them.

The np.array() function is a general-purpose tool for creating and manipulating arrays in the Python programming language. It converts any iterable object to an array of the same type.

It is not a function in the same sense as len() or str() is, but a factory function or class. The constructor can take any number of arguments. For example, we used the np.array() function to create a numpy.ndarray type array of array1, array2, and array3.

Manually create array of arrays

You can directly create array of arrays by specifying array elements to np.array() method.

Here is an example:

Here, we directly passed 2d array to np.array() method to create array of arrays in Python.

Use numpy.append() Function

To generate an array of the array(s) in Python:

  • Use the np.append() function that appends arrays to generate a numpy.ndarray type array.

We already discussed the numpy library and np.array() function while explaining the code snippet for creating an array of arrays using the numpy.array() function.

The np.append() is a built-in function in the numpy library that adds one iterable object to another in Python. It takes arguments as:

  • The arr to add an iterable at its end.
  • The values to add at the end of arr.
  • The axis to append the values along. By default, it flattens the arr and the values.

We used the np.append() function to append array2 and array3 to the end of array1. In addition, we defined axis=0 to make a multi-dimensional array from the arrays instead of flattening them.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *