Last modified: Mar 25, 2026 By Alexander Williams

NumPy Arrays in Python: Complete Guide

NumPy arrays are the foundation of scientific computing in Python. They provide a powerful way to store and manipulate numerical data. This guide will teach you everything you need to know.

You will learn how to create, access, and modify NumPy arrays. We will also cover essential operations and functions. By the end, you will be comfortable using this crucial tool.

What is a NumPy Array?

A NumPy array is a grid of values. All items in the array are of the same type. It is indexed by a tuple of non-negative integers.

The number of dimensions is the rank of the array. The shape is a tuple of integers giving the size along each dimension. NumPy's array class is called ndarray.

It is also known by the alias array. The main advantage over Python lists is speed and functionality. Arrays enable efficient operations on large datasets.

Installing and Importing NumPy

First, you need to install the NumPy library. Use the package installer for Python (pip). Open your terminal or command prompt.


pip install numpy
    

Once installed, import it into your Python script. The standard convention is to import it as np. This makes your code shorter and more readable.

 
import numpy as np  # Standard import for NumPy
    

Creating NumPy Arrays

You can create arrays from Python lists or tuples. Use the np.array() function. Pass your list as an argument.

 
import numpy as np

# Create a 1-D array from a list
my_list = [1, 2, 3, 4, 5]
arr_1d = np.array(my_list)
print("1-D Array:", arr_1d)

# Create a 2-D array from a list of lists
list_2d = [[1, 2, 3], [4, 5, 6]]
arr_2d = np.array(list_2d)
print("\n2-D Array:")
print(arr_2d)
    

1-D Array: [1 2 3 4 5]

2-D Array:
[[1 2 3]
 [4 5 6]]
    

NumPy provides helper functions for common arrays. Use np.zeros() to create an array of zeros. Use np.ones() for an array of ones.

Use np.arange() to create arrays with a range of values. It is similar to Python's range() function. Use np.linspace() for linearly spaced numbers.

 
import numpy as np

# Array of 5 zeros
zero_arr = np.zeros(5)
print("Zeros:", zero_arr)

# 2x3 array of ones
ones_arr = np.ones((2, 3))
print("\nOnes (2x3):")
print(ones_arr)

# Array from 0 to 9
range_arr = np.arange(10)
print("\nArrange (0-9):", range_arr)

# 5 numbers between 0 and 1
lin_arr = np.linspace(0, 1, 5)
print("\nLinspace:", lin_arr)
    

Zeros: [0. 0. 0. 0. 0.]

Ones (2x3):
[[1. 1. 1.]
 [1. 1. 1.]]

Arrange (0-9): [0 1 2 3 4 5 6 7 8 9]

Linspace: [0.   0.25 0.5  0.75 1.  ]
    

Array Attributes: Shape, Size, and Dtype

Every NumPy array has important attributes. They tell you about the array's structure. The shape attribute returns a tuple of array dimensions.

The size attribute gives the total number of elements. The dtype attribute shows the data type of the elements. Understanding these is key to effective array manipulation.

 
import numpy as np

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

print("Array:")
print(arr)
print("\nShape:", arr.shape)   # (2, 3) -> 2 rows, 3 columns
print("Size:", arr.size)       # 6 total elements
print("Data Type (dtype):", arr.dtype) # int64 (or similar)
print("Number of Dimensions (ndim):", arr.ndim)
    

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

Shape: (2, 3)
Size: 6
Data Type (dtype): int64
Number of Dimensions (ndim): 2
    

Accessing and Modifying Array Elements

You access elements using indexing and slicing. It works similarly to Python lists. For multi-dimensional arrays, use a comma-separated tuple of indices.

Our Python Array Indexing Guide for Beginners covers this in great detail. Remember, indexing in Python starts at 0.

 
import numpy as np

arr = np.array([10, 20, 30, 40, 50])

print("Original Array:", arr)
print("Element at index 2:", arr[2])  # Gets 30
print("Elements from index 1 to 3:", arr[1:4]) # Gets [20, 30, 40]

# Modify an element
arr[0] = 99
print("\nArray after modification:", arr)
    

Original Array: [10 20 30 40 50]
Element at index 2: 30
Elements from index 1 to 3: [20 30 40]

Array after modification: [99 20 30 40 50]
    

For 2D arrays, use arr[row, column] syntax. Slicing works on both rows and columns. This is a powerful way to extract sub-arrays.

 
import numpy as np

arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print("2D Array:")
print(arr_2d)
print("\nElement at row 1, column 2:", arr_2d[1, 2]) # Gets 6
print("First row:", arr_2d[0, :])  # Gets [1, 2, 3]
print("Second column:", arr_2d[:, 1]) # Gets [2, 5, 8]
    

2D Array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Element at row 1, column 2: 6
First row: [1 2 3]
Second column: [2 5 8]
    

For a deeper dive into extracting parts of an array, see our Python Array Slicing: A Complete Guide.

Basic Array Operations

NumPy allows arithmetic operations on entire arrays. You can add, subtract, multiply, and divide arrays. These operations are performed element-wise.

This is much faster than using loops in Python. It is a core feature of vectorized computation. Let's look at some examples.

 
import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

print("Array a:", a)
print("Array b:", b)
print("\na + b =", a + b)  # Element-wise addition
print("a - b =", a - b)  # Element-wise subtraction
print("a * b =", a * b)  # Element-wise multiplication
print("b / a =", b / a)  # Element-wise division
print("a ** 2 =", a ** 2) # Square each element
    

Array a: [1 2 3]
Array b: [4 5 6]

a + b = [5 7 9]
a - b = [-3 -3 -3]
a * b = [ 4 10 18]
b / a = [4.  2.5 2. ]
a ** 2 = [1 4 9]
    

Useful Array Functions

NumPy comes with a vast library of mathematical functions. They operate on entire arrays without the need for loops. This is essential for data analysis and science.

You can find sums, means, minimums, and maximums. You can also reshape arrays and join them together. Let's explore a few key functions.

 
import numpy as np

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

print("Array:")
print(arr)
print("\nSum of all elements:", np.sum(arr))
print("Sum along columns (axis=0):", np.sum(arr, axis=0))
print("Sum along rows (axis=1):", np.sum(arr, axis=1))
print("\nMean of all elements:", np.mean(arr))
print("Maximum value:", np.max(arr))
print("Minimum value:", np.min(arr))
    

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

Sum of all elements: 21
Sum along columns (axis=0): [5 7 9]
Sum along rows (axis=1): [9 12]

Mean of all elements: 3.5
Maximum value: 6
Minimum value: 1
    

For a specific example of finding maximum values, check out our guide on how to Find Max of 3 Numbers in Python Array.

Reshaping and Combining Arrays

You can change the shape of an array without changing its data. Use the reshape() method. The total number of elements must stay the same.

You can also stack arrays vertically or horizontally. Use vstack() and hstack(). This is useful for building datasets.

 
import numpy as np

arr = np.arange(12) # Array from 0 to 11
print("Original 1D array:", arr)

# Reshape to 3 rows, 4 columns
reshaped = arr.reshape(3, 4)
print("\nReshaped to 3x4:")
print(reshaped)

# Stacking arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print("\nArray a:", a)
print("Array b:", b)
print("Vertical stack:")
print(np.vstack((a, b)))
print("Horizontal stack:")
print(np.hstack((a, b)))
    

Original 1D array: [ 0  1  2  3  4  5  6  7  8  9 10 11]

Reshaped to 3x4:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Array a: [1 2 3]
Array b: [4 5 6]
Vertical stack:
[[1 2 3]
 [4 5 6]]
Horizontal stack:
[1 2 3 4 5 6]
    

NumPy Array vs Python List

It's important to know when to use a NumPy array versus a Python list. Lists are more flexible and can hold different data types. Arrays are more efficient for numerical computations.

Arrays consume less memory for large datasets. They enable fast vectorized operations. For a detailed comparison, read our article on Python Array vs List: Key Differences Explained.

Conclusion

NumPy arrays are a cornerstone of Python for data science. They provide efficient storage and operations for numerical data. You learned how to create, access, and modify them.

We covered key attributes, operations, and useful functions. Mastering arrays is the first step toward using libraries like Pandas and SciPy. Start practicing with small arrays to build your confidence.

The power of vectorized computation will save you time and effort. Keep exploring the vast NumPy documentation for more advanced features. Happy coding!