Open In App

NumPy Array in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Python lists are a substitute for arrays, but they fail to deliver the performance required while computing large sets of numerical data.

To address this issue we use the NumPy library of Python. NumPy offers an array object called ndarray. They are similar to standard Python sequences but differ in certain key factors.

What is a NumPy Array?

NumPy array is a multi-dimensional data structure that is the core of scientific computing in Python.

All values in an array are homogenous (of the same data type).

They offer automatic vectorization and broadcasting.

They provide efficient memory management, ufuncs(universal functions), support various data types, and are flexible with Indexing and slicing. 

Dimensions in Arrays

NumPy arrays can have multiple dimensions, allowing users to store data in multilayered structures.

Dimensionalities of array:

Name Example
0D (zero-dimensional) Scalar – A single element
1D (one-dimensional) Vector- A list of integers.
2D (two-dimensional) Matrix- A spreadsheet of data
3D (three-dimensional) Tensor- Storing a color image

Create Array Object

NumPy array’s objects allow us to work with arrays in Python. The array object is called ndarray.

array() function of the NumPy library creates a ndarray.

Python3




import numpy as np
arr = np.array([1,2,3,4,5,6])


Output

[1,2,3,4,5,6]

We can also create a NumPy array using List and Tuple.

Create NumPy Array from a List

You can use the np alias to create ndarray of a list using the array() method.

li = [1,2,3,4]
numpyArr = np.array(li)

or

numpyArr = np.array([1,2,3,4])

The list is passed to the array() method which then returns a array with the same elements.

Example 1: The following example shows how to initialize a array from a list. 

Python3




import numpy as np
  
li = [1, 2, 3, 4]
numpyArr = np.array(li)
print(numpyArr)


Output:

[1 2 3 4]

The resulting array looks the same as a list but is a NumPy object. 

Example 2: Let’s take an example to check whether the numpyArr is a NumPy object or not. In this example, we are using the array() function to convert the list into a NumPy array and then check if it’s a NumPy object or not.

Python3




import numpy as np
  
li = [1, 2, 3, 4]
numpyArr = np.array(li)
  
print("li =", li, "and type(li) =", type(li))
print("numpyArr =", numpyArr, "and type(numpyArr) =", type(numpyArr))


Output:

li = [1, 2, 3, 4] and type(li) = <class 'list'>
numpyArr = [1 2 3 4] and type(numpyArr) = <class 'numpy.ndarray'>

As you can see li is a list object whereas numpyArr is an array object of NumPy.

Create a NumPy Array from a Tuple

You can make ndarray from a tuple using a similar syntax.

tup = (1,2,3,4)
numpyArr = np.array(tup)

or

numpyArr = np.array((1,2,3,4))

The following example illustrates how to create a array from a tuple. Here, we are using the array() function to convert the tuple to a NumPy array.

Python3




import numpy as np
  
tup = (1, 2, 3, 4)
numpyArr = np.array(tup)
  
print("tup =", tup, "and type(tup) =", type(tup))
print("numpyArr =", numpyArr, "and type(numpyArr) =", type(numpyArr))


Output:

tup = (1, 2, 3, 4) and type(tup) = <class 'tuple'>
numpyArr = [1 2 3 4] and type(numpyArr) = <class 'numpy.ndarray'>

Note that the value of numpyArr remains the same for either of the two conversions.

NumPy Arrays vs Inbuilt Python Sequences

  • Unlike lists, arrays are of fixed size, and changing the size of an array will lead to the creation of a new array while the original array will be deleted.
  • All the elements in an array are of the same type.
  • Arrays are faster, more efficient, and require less syntax than standard Python sequences.

Note: Various scientific and mathematical Python-based packages use Numpy. They might take input as an inbuilt Python sequence but they are likely to convert the data into a NumPy array to attain faster processing. This explains the need to understand NumPy.

Why is the Numpy Array so Fast?

Numpy arrays are written mostly in C language. Being written in C, the arrays are stored in contiguous memory locations which makes them accessible and easier to manipulate. This means that you can get the performance level of a C code with the ease of writing a Python program.

  1. Homogeneous Data: Arrays store elements of the same data type, making them more compact and memory-efficient than lists.
  2. Fixed Data Type: Arrays have a fixed data type, reducing memory overhead by eliminating the need to store type information for each element.
  3. Contiguous Memory: Arrays store elements in adjacent memory locations, reducing fragmentation and allowing for efficient access.
numpyarray

Numpy Array Memory Allocation

If you don’t have NumPy installed in your system, you can do so by following these steps. After installing NumPy you can import it into your program like this

import numpy as np

Note: Here np is a commonly used alias for NumPy.

Data Allocation in Numpy Array

In NumPy, data is allocated contiguously in memory, following a well-defined layout consisting of the data buffer, shape, and strides. This is essential for efficient data access, vectorized operations, and compatibility with low-level libraries like BLAS and LAPACK.

  1. Data Buffer: The data buffer in NumPy is a single, flat block of memory that stores the actual elements of the array, regardless of its dimensionality. This enables efficient element-wise operations and data access.
  2. Shape: The shape of an array is a tuple of integers that represents the dimensions along each axis. Each integer corresponds to the size of the array along a specific dimension, which defines the number of elements along each axis and is essential for correctly indexing and reshaping the array.
  3. Strides: Strides are tuples of integers that define the number of bytes to step in each dimension when moving from one element to the next. They determine the spacing between elements in memory and measure how many bytes are required to move from one element to another in each dimension.

2

Conclusion

NumPy array in Python is a very useful data structure and it allows us to perform various scientific operations on the data. It is a very memory-efficient data structure and offers a wide variety of advantages over other Python sequences. 

In this tutorial, we have explained NumPy arrays in detail. We have covered the definition, dimensionality, why is it fast, and how data allocation works in an array. After completing this tutorial you will gain complete in-depth knowledge of NumPy array and will be able to implement it in your Python projects.



Last Updated : 01 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads