Skip to main content

Python Arrays

Python arrays with code examples. Learn how to create and print arrays using Python NumPy today!
Updated Aug 8, 2024  · 3 min read

Arrays are fundamental data structures in many programming languages, providing a way to store collections of elements of the same type in a contiguous block of memory—meaning all elements are stored sequentially without gaps. This structure allows for efficient access and manipulation of the stored elements.

Unlike languages such as C or Java, Python does not have a built-in array data type in the traditional sense. Instead, Python provides several alternatives that function like arrays, each suited for different programming needs and scenarios.

Python’s standard library includes an array module, which allows for the creation of compact, type-restricted arrays similar to those in more statically-typed languages.

For numerical and scientific computing, however, the NumPy library and its ndarray (n-dimensional array) have become the go-to standard in Python. NumPy arrays provide extensive functionality far beyond the basic array structure offered by Python’s standard library.

AI Upskilling for Beginners

Learn the fundamentals of AI and ChatGPT from scratch.
Learn AI for Free

Basics of an Array

NumPy is the fundamental package for numerical computing in Python, offering a powerful array object and a suite of functions for working efficiently with these arrays. The advantages of Numpy are:

Multidimensional: Supports more than just one-dimensional arrays.

Powerful operations: Includes a vast library of mathematical and statistical functions.

Vectorization: Allows for operations on entire arrays without the need for explicit loops, enhancing performance.

Integration: Works seamlessly with other scientific libraries like SciPy, Pandas, and Matplotlib.

Let's start creating an array using Numpy. You first import NumPy and then use the array() function to create an array. The array() function takes a list as an input.

import numpy
my_array = numpy.array([0, 1, 2, 3, 4])
print(my_array)
[0, 1, 2, 3, 4]

The type of my_array is a numpy.ndarray.

print(type(my_array))
<class 'numpy.ndarray'>

Array Examples

Example of creating an Array

In the below example, you will convert a list to an array using the array() function from NumPy. You will create a list a_list comprising of integers. Then, using the array() function, convert it an array.

import numpy as np

a_list = [1, 2, 3, 4]
a_list
[1, 2, 3, 4]
an_array = np.array(a_list)
an_array
array([1, 2, 3, 4])

Example of an Array operation

In the below example, you add two numpy arrays. The result is an element-wise sum of both the arrays.

import numpy as np

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

print(array_A + array_B)
[5 7 9]

Example of Array indexing

You can select a specific index element of an array using indexing notation.

import numpy as np

months_array = np.array(['Jan', 'Feb', 'March', 'Apr', 'May'])
print(months_array[3])
Apr

You can also slice a range of elements using the slicing notation specifying a range of indices.

print(months_array[2:5])
['March', 'Apr', 'May']

Interactive Example of a List to an Array

In the below example, you will import numpy using the alias np. Create prices_array and earnings_array arrays from the lists prices and earnings, respectively. Finally, print both the arrays.

# IMPORT numpy as np
import numpy as np

# Lists
prices = [170.12, 93.29, 55.28, 145.30, 171.81, 59.50, 100.50]
earnings = [9.2, 5.31, 2.41, 5.91, 15.42, 2.51, 6.79]

# NumPy arrays
prices_array = np.array(prices)
earnings_array = np.array(earnings)

# Print the arrays
print(prices_array)
print(earnings_array)

When you run the above code, it produces the following result:

[170.12  93.29  55.28 145.3  171.81  59.5  100.5 ]
[ 9.2   5.31  2.41  5.91 15.42  2.51  6.79]

Try it for yourself.

To learn more about NumPy arrays in Python, please see this video from our course Introduction to Python for Finance.

This content is taken from DataCamp’s Introduction to Python for Finance course by Adina Howe.

Check out our Python Numpy Array Tutorial.

FAQs

What are the main differences between Python’s array module and NumPy arrays?

The main differences lie in capabilities and use cases. Python’s array module provides basic functionality for creating compact, type-restricted arrays similar to those in languages like C. On the other hand, NumPy arrays offer advanced features such as support for multidimensional arrays, a vast library of mathematical functions, and performance optimizations through vectorization. NumPy is generally preferred for numerical and scientific computing.

Can I use Python’s array module for string or object data types?

No, the array module is designed to hold only basic data types like integers, floats, and similar. It does not support strings or objects. For collections of these types, Python’s list or other data structures like tuples or dictionaries are more appropriate.

Why use NumPy arrays over Python lists for numerical data?

NumPy arrays are specifically optimized for numerical computations. They provide efficient storage and processing capabilities that surpass Python lists, especially for large datasets. Features like vectorization allow for operations on entire arrays without explicit loops, greatly enhancing performance and readability of the code.

Topics

Learn more about Python

course

Introduction to NumPy

4 hr
37.3K
Master your skills in NumPy by learning how to create, sort, filter, and update arrays using NYC’s tree census.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

cheat-sheet

NumPy Cheat Sheet: Data Analysis in Python

This Python cheat sheet is a quick reference for NumPy beginners.
Karlijn Willems's photo

Karlijn Willems

6 min

cheat-sheet

Pandas Cheat Sheet for Data Science in Python

A quick guide to the basics of the Python data analysis library Pandas, including code samples.
Karlijn Willems's photo

Karlijn Willems

4 min

tutorial

Python Numpy Array Tutorial

A NumPy tutorial for beginners in which you'll learn how to create a NumPy array, use broadcasting, access values, manipulate arrays, and much more.
Karlijn Willems's photo

Karlijn Willems

45 min

tutorial

Scipy Tutorial: Vectors and Arrays (Linear Algebra)

A SciPy tutorial in which you'll learn the basics of linear algebra that you need for machine learning in Python, with a focus how to with NumPy.
Karlijn Willems's photo

Karlijn Willems

28 min

tutorial

Python Tutorial for Beginners

Get a step-by-step guide on how to install Python and use it for basic data science functions.
Matthew Przybyla's photo

Matthew Przybyla

12 min

code-along

NumPy Crash Course

Learn about NumPy arrays and manipulate data stored inside of them.
Izzy Weber's photo

Izzy Weber

See MoreSee More