The Wayback Machine - https://web.archive.org/web/20241004114145/https://www.geeksforgeeks.org/numpy-array-in-python/
Open In App

NumPy Array in Python

Last Updated : 01 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Previous Article
Next Article

Similar Reads

NumPy Array Sorting | How to sort NumPy Array
Sorting an array is a very important step in data analysis as it helps in ordering data, and makes it easier to search and clean. In this tutorial, we will learn how to sort an array in NumPy. You can sort an array in NumPy: Using np.sort() functionin-line sortsorting along different axesUsing np.argsort() functionUsing np.lexsort() functionUsing s
4 min read
Difference between Numpy array and Numpy matrix
While working with Python many times we come across the question that what exactly is the difference between a numpy array and numpy matrix, in this article we are going to read about the same. What is np.array() in PythonThe Numpy array object in Numpy is called ndarray. We can create ndarray using numpy.array() function. It is used to convert a l
3 min read
NumPy ndarray.tolist() Method | Convert NumPy Array to List
The ndarray.tolist() method converts a NumPy array into a nested Python list. It returns the array as an a.ndim-levels deep nested list of Python scalars. Data items are converted to the nearest compatible built-in Python type. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) print(gfg.tolist()) Output[1, 2, 3, 4, 5] SyntaxSynt
1 min read
NumPy ndarray.size() Method | Get Number of Elements in NumPy Array
The ndarray.size() method returns the number of elements in the NumPy array. It works the same as np.prod(a.shape), i.e., the product of the dimensions of the array. Example C/C++ Code import numpy as np arr = np.zeros((3, 4, 2), dtype = np.complex128) gfg = arr.size print (gfg) Output : 24Syntax Syntax: numpy.ndarray.size(arr) Parameters arr : [ar
1 min read
NumPy ndarray.__abs__() | Find Absolute Value of Elements in NumPy Array
The ndarray.__abs__() method returns the absolute value of every element in the NumPy array. It is automatically invoked when we use Python's built-in method abs() on a NumPy array. Example C/C++ Code import numpy as np gfg = np.array([1.45, 2.32, 3.98, 4.41, 5.55, 6.12]) print(gfg.__abs__()) Output[ 1 2 3 4 5 6] SyntaxSyntax: ndarray.__abs__() Ret
1 min read
NumPy ndarray.__ilshift__() | Shift NumPy Array Elements to Left
The ndarray.__ilshift__() method is an in-place left-shift operation. It shifts elements in the array to the left of the number of positions specified. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__ilshift__() method print(gfg.__ilshift__(2)) Output[ 4 8 12 16 20] SyntaxSyntax: ndarray.__ilshift__($self,
1 min read
NumPy ndarray.__irshift__() | Shift NumPy Array Elements to Right
The ndarray.__irshift__() method returns a new array where each element is right-shifted by the value that is passed as a parameter. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__irshift__() method print(gfg.__irshift__(2)) Output[0 0 0 1 1] SyntaxSyntax: ndarray.__irshift__($self, value, /) Parameter se
1 min read
NumPy ndarray.imag() Method | Get Imaginary Part in NumPy Array
The ndarray.imag() method returns the imaginary part of the complex number in the NumPy array. Note: Remember resulting data type for the imaginary value is 'float64'. Example C/C++ Code # import the important module in python import numpy as np # make an array with numpy gfg = np.array([1 + 2j, 2 + 3j]) # applying ndarray.imag() method geeks = np.
1 min read
NumPy ndarray.transpose() Method | Find Transpose of the NumPy Array
The ndarray.transpose() function returns a view of the array with axes transposed. For a 1-D array, this has no effect, as a transposed vector is simply the same vector.For a 2-D array, this is a standard matrix transpose.For an n-D array, if axes are given, their order indicates how the axes are permuted. If axes are not provided and arr.shape = (
2 min read
Python | Numpy numpy.transpose()
With the help of Numpy numpy.transpose(), We can perform the simple function of transpose within one line by using numpy.transpose() method of Numpy. It can transpose the 2-D arrays on the other hand it has no effect on 1-D arrays. This method transpose the 2-D numpy array. Parameters: axes : [None, tuple of ints, or n ints] If anyone wants to pass
2 min read
Python | Numpy numpy.ndarray.__lt__()
With the help of numpy.ndarray.__lt__() method of Numpy, We can find that which element in an array is less than the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__lt__($self, value, /) Return: self<value Example #1 : In this example we can see that
1 min read
Python | Numpy numpy.ndarray.__gt__()
With the help of numpy.ndarray.__gt__() method of Numpy, We can find that which element in an array is greater then the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__gt__($self, value, /) Return: self>value Example #1 : In this example we can see th
1 min read
Python | Numpy numpy.ndarray.__le__()
With the help of numpy.ndarray.__le__() method of Numpy, We can find that which element in an array is less than or equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__le__($self, value, /) Return: self<=value Example #1 : In this example we
1 min read
Python | Numpy numpy.ndarray.__ge__()
With the help of numpy.ndarray.__ge__() method of Numpy, We can find that which element in an array is greater then or equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__ge__($self, value, /) Return: self>=value Example #1 : In this example
1 min read
Python | Numpy numpy.ndarray.__ne__()
With the help of numpy.ndarray.__ne__() method of Numpy, We can find that which element in an array is not equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__ne__($self, value, /) Return: self!=value Example #1 : In this example we can see that
1 min read
Python | Numpy numpy.ndarray.__neg__()
With the help of numpy.ndarray.__neg__() method of Numpy, one can multiply each and every element of an array with -1. Hence, the resultant array having values like positive values becomes negative and negative values become positive. Syntax: ndarray.__neg__($self, /) Return: -self Example #1 : In this example we can see that after applying numpy._
1 min read
Python | Numpy numpy.ndarray.__pos__()
With the help of numpy.ndarray.__pos__() method of Numpy, one can multiply each and every element of an array with 1. Hence, the resultant array having values same as original array. Syntax: ndarray.__pos__($self, /) Return: +self Example #1 : In this example we can see that after applying numpy.__pos__(), we get the simple array that can be the sa
1 min read
Python | Numpy numpy.ndarray.__sub__()
With the help of Numpy numpy.ndarray.__sub__(), We can subtract a particular value that is provided as a parameter in the ndarray.__sub__() method. Value will be subtracted to each and every element in a numpy array. Syntax: ndarray.__sub__($self, value, /) Return: self-value Example #1 : In this example we can see that each and every element in an
1 min read
Python | Numpy numpy.ndarray.__add__()
With the help of Numpy numpy.ndarray.__add__(), we can add a particular value that is provided as a parameter in the ndarray.__add__() method. Value will be added to each and every element in a numpy array. Syntax: ndarray.__add__($self, value, /) Return: self+value Example #1 : In this example we can see that each and every element in an array is
1 min read
Python | Numpy numpy.ndarray.__floordiv__()
With the help of Numpy numpy.ndarray.__floordiv__(), one can divide a particular value that is provided as a parameter in the ndarray.__floordiv__() method. Value will be divided to each and every element in a numpy array and remember it always gives the floor value after division. Syntax: ndarray.__floordiv__($self, value, /) Return: self//value E
1 min read
Python | Numpy numpy.ndarray.__mod__()
With the help of Numpy numpy.ndarray.__mod__(), every element in an array is operated on binary operator i.e mod(%). Remember we can use any type of values in an array and value for mod is applied as the parameter in ndarray.__mod__(). Syntax: ndarray.__mod__($self, value, /) Return: self%value Example #1 : In this example we can see that value tha
1 min read
Python | Numpy numpy.ndarray.__divmod__()
With the help of Numpy numpy.ndarray.__divmod__() method, we will get two arrays one is having elements that is divided by value that is provided in numpy.ndarray.__divmod__() method and second is having elements that perform mod operation with same value as provided in numpy.ndarray.__divmod__() method. Syntax: ndarray.__divmod__($self, value, /)
1 min read
Python | Numpy numpy.ndarray.__rshift__()
With the help of numpy.ndarray.__rshift__() method, we can get the elements that is right shifted by the value that is provided as a parameter in numpy.ndarray.__rshift__() method. Syntax: ndarray.__rshift__($self, value, /) Return: self>>value Example #1 : In this example we can see that every element is right shifted by the value that is pa
1 min read
Python | Numpy numpy.ndarray.__lshift__()
With the help of Numpy numpy.ndarray.__lshift__() method, we can get the elements that is left shifted by the value that is provided as a parameter in numpy.ndarray.__lshift__() method. Syntax: ndarray.__lshift__($self, value, /) Return: self<<value Example #1 : In this example we can see that every element is left shifted by the value that i
1 min read
Python | Numpy numpy.ndarray.__imul__()
With the help of numpy.ndarray.__imul__() method, we can multiply a particular value that is provided as a parameter in the ndarray.__imul__() method. Value will be multiplied to every element in a numpy array. Syntax: ndarray.__imul__($self, value, /)Return: self*=value Example #1 : In this example we can see that each and every element in an arra
1 min read
Python | Numpy numpy.ndarray.__isub__()
With the help of numpy.ndarray.__isub__() method, we can subtract a particular value that is provided as a parameter in the ndarray.__isub__() method. Value will be subtracted to every element in a numpy array. Syntax: ndarray.__isub__($self, value, /) Return: self-=value Example #1 : In this example we can see that each and every element in an arr
1 min read
Python | Numpy numpy.ndarray.__iadd__()
With the help of numpy.ndarray.__iadd__() method, we can add a particular value that is provided as a parameter in the ndarray.__iadd__() method. Value will be added to every element in a numpy array. Syntax: ndarray.__iadd__($self, value, /) Return: self+=value Example #1 : In this example we can see that each and every element in an array is adde
1 min read
Python | Numpy numpy.ndarray.__xor__()
With the help of Numpy numpy.ndarray.__xor__() method, we can get the elements that is XOR by the value that is provided as a parameter in numpy.ndarray.__xor__() method. Syntax: ndarray.__xor__($self, value, /) Return: self^value Example #1 : In this example we can see that every element is xor by the value that is passed as a parameter in ndarray
1 min read
Python | Numpy numpy.ndarray.__and__()
With the help of Numpy numpy.ndarray.__and__() method, we can get the elements that is anded by the value that is provided as a parameter in numpy.ndarray.__and__() method. Syntax: ndarray.__and__($self, value, /) Return: self&value Example #1 : In this example we can see that every element is anded by the value that is passed as a parameter in
1 min read
Python | Numpy numpy.ndarray.__or__()
With the help of Numpy numpy.ndarray.__or__() method, we can get the elements that is OR by the value that is provided as a parameter in numpy.ndarray.__or__() method. Syntax: ndarray.__or__($self, value, /) Return: self|value Example #1 : In this example we can see that every element is or by the value that is passed as a parameter in ndarray.__or
1 min read
Practice Tags :