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 a python library called NumPy. The word NumPy stands for Numerical Python. NumPy offers an array object called ndarray. They are similar to standard python sequences but differ in certain key factors.
NumPy arrays vs inbuilt Python sequences
- Unlike lists, NumPy 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.
- Numpy 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 in order to attain faster processing. This explains the need to understand NumPy.
Why is Numpy so fast?
Numpy arrays are written mostly in C language. Being written in C, the NumPy 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.
Using Numpy Arrays
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 in your program like this
import numpy as np
Here np is a commonly used alias to NumPy.
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)
numpyArr = np.array([1,2,3,4])
The list is passed to the array() method which then returns a NumPy array with the same elements.
The following example shows how to initialize a NumPy array from a list.
[1 2 3 4]
The resulting array looks the same as a list but is actually a NumPy object.
Example: Let’s take an example to check whether the numpyArr is a NumPy object or not.
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.
NumPy array from a tuple
You can make ndarray from a tuple using similar syntax.
tup = (1,2,3,4) numpyArr = np.array(tup)
numpyArr = np.array((1,2,3,4))
The following example illustrates how to create a NumPy array from a tuple.
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.