DEV Community

Cover image for NumPy Arrays for Beginners: A Better Alternative to Python Lists
Sophia Okosodo
Sophia Okosodo

Posted on

NumPy Arrays for Beginners: A Better Alternative to Python Lists

NumPy is a highly popular Python package. One of its best features is the NumPy array (officially known as ndarray). You can think of it as a cleaner, much faster version of a standard Python list.

Although NumPy arrays resemble Python lists, they offer a significant advantage: you can perform mathematical operations on the entire array at once. These operations are simple to write and execute very efficiently.

Example
Suppose you have two lists:

heights = [2.40, 3.21, 1.34, 3.45]
weights = [45.0, 68.3, 34.1, 82.0]
Enter fullscreen mode Exit fullscreen mode

Attempting to calculate the Body Mass Index (BMI) directly with lists produces an error:

bmi = weights / (heights ** 2)
Enter fullscreen mode Exit fullscreen mode

*Error: *

TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
Enter fullscreen mode Exit fullscreen mode

Python lists do not support element-wise mathematical operations. To achieve the same result with regular lists, you would need to loop through each element individually. This approach is slow and inefficient, especially with large data.

This is where NumPy comes in

NumPy allows us to perform these calculations efficiently by converting the lists into NumPy arrays:

import numpy as np

np_height = np.array(heights)
np_weight = np.array(weights)

bmi = np_weight / np_height ** 2
bmi
Enter fullscreen mode Exit fullscreen mode

This code runs successfully and returns a new array containing the BMI values for each corresponding pair:

array([ 7.8125    ,  6.62842946, 18.99086656,  6.88930897])
Enter fullscreen mode Exit fullscreen mode

Important Note:
Unlike Python lists, NumPy arrays can only contain elements of the same data type. If you try to create an array with mixed types, NumPy will automatically convert all elements to a single common type.

Example:

np.array([1.0, 'is', True])
Enter fullscreen mode Exit fullscreen mode

Output:

array(['1.0', 'is', 'True'], dtype='<U32')
Enter fullscreen mode Exit fullscreen mode

In summary, NumPy lets you apply math to entire arrays at once, making your calculations fast and efficient.

Top comments (0)