NumPy Tutorial · NumPy Tutorial

NumPy Creating Arrays

Learn all about NumPy Creating Arrays in this comprehensive tutorial.

5 min read intermediate
  • NumPy is used to work with arrays.
  • A dimension in arrays is one level of array depth (nested arrays).
  • 0-D arrays, or Scalars, are the elements in an array.
  • An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
  • An array that has 1-D arrays as its elements is called a 2-D array.
  • An array that has 2-D arrays (matrices) as its elements is called 3-D array.
  • NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array have.
  • An array can have any number of dimensions.

Create a NumPy ndarray Object

NumPy is used to work with arrays. The array object in NumPy is called ndarray.

We can create a NumPy ndarray object by using the array() function.

python
Note: type(): This built-in Python function tells us the type of the object passed to it. Like in above code it shows that arr is numpy.ndarray type.

To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will be converted into an ndarray:

python

Dimensions in Arrays

A dimension in arrays is one level of array depth (nested arrays).

Note: nested array: are arrays that have arrays as their elements.

0-D Arrays

0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.

python

1-D Arrays

An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.

These are the most common and basic arrays.

python

2-D Arrays

An array that has 1-D arrays as its elements is called a 2-D array.

These are often used to represent matrix or 2nd order tensors.

Note: NumPy has a whole sub module dedicated towards matrix operations called numpy.mat
python

3-D arrays

An array that has 2-D arrays (matrices) as its elements is called 3-D array.

These are often used to represent a 3rd order tensor.

python

Check Number of Dimensions?

NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array have.

python

Higher Dimensional Arrays

An array can have any number of dimensions.

When the array is created, you can define the number of dimensions by using the ndmin argument.

python

In this array the innermost dimension (5th dim) has 4 elements, the 4th dim has 1 element that is the vector, the 3rd dim has 1 element that is the matrix with the vector, the 2nd dim has 1 element that is 3D array and 1st dim has 1 element that is a 4D array.

Module quiz

2 questions
1

Which of the following is true about NumPy Creating Arrays?

2

What is the most common pitfall when working with NumPy Creating Arrays?

Answer all questions to submit.