The Wayback Machine - https://web.archive.org/web/20241002052419/https://www.geeksforgeeks.org/python-lists-vs-numpy-arrays/
Open In App

Python Lists VS Numpy Arrays

Last Updated : 25 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Here, we will understand the difference between Python List and Python Numpy array.

What is a Numpy array?

NumPy is the fundamental package for scientific computing in Python. Numpy arrays facilitate advanced mathematical and other types of operations on large numbers of data. Typically, such operations are executed more efficiently and with less code than is possible using Python’s built-in sequences. Numpy is not another programming language but a Python extension module. It provides fast and efficient operations on arrays of homogeneous data. 

Some important points about Numpy arrays:

  • We can create an N-dimensional array in Python using Numpy.array().
  • The array is by default Homogeneous, which means data inside an array must be of the same Datatype. (Note You can also create a structured array in Python).
  • Element-wise operation is possible.
  • Numpy array has various functions, methods, and variables, to ease our task of matrix computation.
  • Elements of an array are stored contiguously in memory. For example, all rows of a two-dimensioned array must have the same number of columns. A three-dimensional array must have the same number of rows and columns on each card.

Representation of Numpy array

  • Single Dimensional Numpy Array

Python3




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


O

[1 2 3]
  • Multi-dimensional Numpy Array

Python3




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


Output:

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

What is Python List?

A Python list is a collection that is ordered and changeable. In Python, lists are written with square brackets. 

Some important points about Python Lists:

  • The list can be homogeneous or heterogeneous.
  • Element-wise operation is not possible on the list.
  • Python list is by default 1-dimensional. But we can create an N-Dimensional list. But then too it will be 1 D list storing another 1D list
  • Elements of a list need not be contiguous in memory.

Below are some examples which clearly demonstrate how Numpy arrays are better than Python lists by analyzing the memory consumption, execution time comparison, and operations supported by both of them. 

Representation of Python List

Here we are creating Python List using []

Python3




Var = ["Geeks", "for", "Geeks"]
print(Var)


Output:

["Geeks", "for", "Geeks"]

Comparison between Numpy array and Python List

Python Lists

  1. Element Overhead: Lists in Python store additional information about each element, such as its type and reference count. This overhead can be significant when dealing with a large number of elements.
  2. Datatype: Lists can hold different data types, but this can decrease memory efficiency and slow numerical operations.
  3. Memory Fragmentation: Lists may not store elements in contiguous memory locations, causing memory fragmentation and inefficiency.
  4. Performance: Lists are not optimized for numerical computations and may have slower mathematical operations due to Python’s interpretation overhead. They are generally used as general-purpose data structures.
  5. Functionality: Lists can store any data type, but lack specialized NumPy functions for numerical operations.

Python List vs NumPy Array

Numpy Arrays

  1. Homogeneous Data: NumPy arrays store elements of the same data type, making them more compact and memory-efficient than lists.
  2. Fixed Data Type: NumPy arrays have a fixed data type, reducing memory overhead by eliminating the need to store type information for each element.
  3. Contiguous Memory: NumPy arrays store elements in adjacent memory locations, reducing fragmentation and allowing for efficient access.
  4. Array Metadata: NumPy arrays have extra metadata like shape, strides, and data type. However, this overhead is usually smaller than the per-element overhead in lists.
  5. Performance: NumPy arrays are optimized for numerical computations, with efficient element-wise operations and mathematical functions. These operations are implemented in C, resulting in faster performance than equivalent operations on lists.

Numpy Array - Numpy VS List

Memory consumption between Numpy array and lists 

In Python, a list is a built-in data structure that can hold elements of varying data types. However, the flexibility of lists comes at the cost of memory efficiency.

Python’s NumPy library supports optimized numerical array and matrix operations.

Demonestration of list and array

Memory Allocation

In this example, a Python list and a Numpy array of size 1000 will be created. The size of each element and then the whole size of both containers will be calculated and a comparison will be done in terms of memory consumption. 

Python3




# importing numpy package
import numpy as np
 
# importing system module
import sys
 
# declaring a list of 1000 elements
S= range(1000)
 
# printing size of each element of the list
print("Size of each element of list in bytes: ",sys.getsizeof(S))
 
# printing size of the whole list
print("Size of the whole list in bytes: ",sys.getsizeof(S)*len(S))
 
# declaring a Numpy array of 1000 elements
D= np.arange(1000)
 
# printing size of each element of the Numpy array
print("Size of each element of the Numpy array in bytes: ",D.itemsize)
 
# printing size of the whole Numpy array
print("Size of the whole Numpy array in bytes: ",D.size*D.itemsize)


Output:

Size of each element of list in bytes:  48 
Size of the whole list in bytes: 48000
Size of each element of the Numpy array in bytes: 8
Size of the whole Numpy array in bytes: 8000

Time comparison between Numpy array and Python lists 

In this example, here two Python lists and two Numpy arrays will be created and each container has 1000000 elements. Multiplication of elements in both the lists and Numpy arrays respectively will be carried out and the difference in time needed for the execution for both the containers will be analyzed to determine which one takes less time to perform the operation.

Python3




# importing required packages
import numpy
import time
 
# size of arrays and lists
size = 1000000
 
# declaring lists
list1 = range(size)
list2 = range(size)
 
# declaring arrays
array1 = numpy.arange(size)
array2 = numpy.arange(size)
 
# capturing time before the multiplication of Python lists
initialTime = time.time()
 
# multiplying elements of both the lists and stored in another list
resultantList = [(a * b) for a, b in zip(list1, list2)]
 
# calculating execution time
print("Time taken by Lists to perform multiplication:",
    (time.time() - initialTime),
    "seconds")
 
# capturing time before the multiplication of Numpy arrays
initialTime = time.time()
 
# multiplying elements of both the Numpy arrays and stored in another Numpy array
resultantArray = array1 * array2
 
# calculating execution time
print("Time taken by NumPy Arrays to perform multiplication:",
    (time.time() - initialTime),
    "seconds")


Output:

Time taken by Lists to perform multiplication: 0.07256507873535156 seconds 
Time taken by NumPy Arrays to perform multiplication: 0.006612300872802734 seconds

Effect of operations on Numpy array and Python Lists 

In this example, the incapability of the Python list to carry out a basic operation is demonstrated. A Python list and a Numpy array having the same elements will be declared and an integer will be added to increment each element of the container by that integer value without looping statements. The effect of this operation on the Numpy array and Python list will be analyzed.

Python3




# importing Numpy package
import numpy as np
 
# declaring a list
ls =[1, 2, 3]
 
# converting the list into a Numpy array
arr = np.array(ls)
 
try:
    # adding 4 to each element of list
    ls = ls + 4
     
except(TypeError):
    print("Lists don't support list + int")
 
# now on array
try:
    # adding 4 to each element of Numpy array
    arr = arr + 4
 
    # printing the Numpy array
    print("Modified Numpy array: ",arr)
     
except(TypeError):
    print("Numpy arrays don't support list + int")


Output:

Lists don't support list + int 
Modified Numpy array: [5 6 7]

Conclusion

Advantages of using Numpy Arrays Over Python Lists:

  • Consumes less memory.
  • Fast as compared to the python List.
  • Convenient to use.


Similar Reads

Convert Python Nested Lists to Multidimensional NumPy Arrays
Prerequisite: Python List, Numpy ndarray Both lists and NumPy arrays are inter-convertible. Since NumPy is a fast (High-performance) Python library for performing mathematical operations so it is preferred to work on NumPy arrays rather than nested lists. Method 1: Using numpy.array(). Approach : Import numpy package.Initialize the nested list and
2 min read
Benefit of NumPy arrays over Python arrays
The need for NumPy arises when we are working with multi-dimensional arrays. The traditional array module does not support multi-dimensional arrays. Let's first try to create a single-dimensional array (i.e one row & multiple columns) in Python without installing NumPy Package to get a more clear picture. C/C++ Code from array import * arr = ar
1 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
Python | Numpy numpy.matrix.any()
With the help of Numpy numpy.matrix.any() method, we are able to compare each and every element of one matrix with another or we can provide the axis on the we want to apply comparison if any of the element matches it return true. Syntax : numpy.matrix.any() Return : Return true if any match found else false Example #1 : In this example we can see
1 min read
Python | Numpy numpy.matrix.all()
With the help of Numpy numpy.matrix.all() method, we are able to compare each and every element of one matrix with another or we can provide the axis on the we want to apply comparison. Syntax : numpy.matrix.all() Return : Return true if found match else false Example #1 : In this example we can see that with the help of matrix.all() method, we are
1 min read
Python | Numpy numpy.matrix.A()
With the help of Numpy numpy.matrix.A() method, we can get the same matrix as self. It means through this method we can get the identical matrix. Syntax : numpy.matrix.A() Return : Return self matrix Example #1 : In this example we can see that with the help of matrix.A() method, we are able to get the self matrix. # import the important module in
1 min read
Python | Numpy numpy.matrix.T()
With the help of Numpy numpy.matrix.T() method, we can make a Transpose of any matrix either having dimension one or more than more. Syntax : numpy.matrix.T() Return : Return transpose of every matrix Example #1 : In this example we can see that with the help of matrix.T() method, we are able to transform any type of matrix. # import the important
1 min read
Python | Numpy numpy.matrix.H()
With the help of Numpy numpy.matrix.H() method, we can make a conjugate Transpose of any complex matrix either having dimension one or more than more. Syntax : numpy.matrix.H() Return : Return conjugate transpose of every complex matrix Example #1 : In this example we can see that with the help of matrix.H() method, we are able to transform any typ
1 min read
Python | Numpy numpy.choose()
With the help of Numpy numpy.choose() method, we can select the elements from an multidimensional array by passing a parameter as an array which contain the index of row number to be selected. Output array having the same size as passed in the parameter. Syntax : numpy.choose() Return : Return an array of element choice Example #1 : In this example
1 min read
Python | Numpy numpy.ndarray.__invert__()
With the help of Numpy numpy.ndarray.__invert__(), one can invert the elements of an array. We don't have to provide any type of parameter but remember that this method only works for integer values. Syntax: ndarray.__invert__($self, /) Return: ~self Example #1 : In this example we can see that every element in an array is operated on a unary opera
1 min read
Practice Tags :