How To Print An Array In Python

5 min read

How to Print an Array in Python

Printing an array is one of the most frequent tasks when you are debugging, displaying results, or preparing data for further analysis. Each of them has its own idiomatic ways to be shown on the screen, and knowing the right technique saves time and avoids confusing output. That said, in Python the term “array” can refer to several different data structures—plain lists, the built‑in array module, or powerful NumPy arrays. This guide walks you through the most common methods, explains when to use each one, and provides practical examples you can copy‑paste into your own scripts.


Understanding What “Array” Means in Python

Before diving into printing techniques, it helps to clarify what you are working with.

Structure Typical Import When to Use Printing Characteristics
list built‑in General purpose, heterogeneous or homogeneous data Prints with square brackets and commas by default
array.g.array from array import array Memory‑efficient storage of numeric types (e., int, float) Behaves like a list but stores items in a C‑style buffer
**numpy.

All three can be printed with the simple print() function, but the default representation may not always be what you want—especially for large or multi‑dimensional data. The sections below show how to tailor the output to your needs And it works..


Basic Printing with the Built‑in print()

The simplest way to display any Python object is to pass it to print(). For a list or an array.array this yields a readable representation:

my_list = [10, 20, 30, 40]
print(my_list)          # Output: [10, 20, 30, 40]

from array import array
my_array = array('i', [10, 20, 30, 40])
print(my_array)         # Output: array('i', [10, 20, 30, 40])

For NumPy arrays the default print is also convenient for small sizes:

import numpy as np
np_arr = np.array([10, 20, 30, 40])
print(np_arr)           # Output: [10 20 30 40]

Notice that NumPy omits commas and uses spaces, which matches the typical layout of numeric matrices.


Printing Elements One‑by‑One

Sometimes you need more control over spacing, line breaks, or you want to label each element. A for loop does the job:

for i, value in enumerate(my_list):
    print(f"Element {i}: {value}")

Output:

Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40

If you prefer a single line with a custom separator, the join() method works well for strings. Convert each item to a string first:

print(" | ".join(str(x) for x in my_list))
# Output: 10 | 20 | 30 | 40

Using pprint for Nested Structures

When dealing with lists of lists (or arrays of arrays) the default print() can become hard to read because everything ends up on one long line. The pprint module (“pretty‑print”) adds line breaks and indentation:

import pprint

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

pprint.pprint(matrix)

Output:

[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]

pprint also respects the width of the terminal and can be customized with width, depth, and compact arguments.


Custom Formatting with str.format() or f‑Strings

For more elaborate layouts—such as aligning numbers in columns—you can combine loops with format specifiers:

print("{:>5} {:>5} {:>5}".format("Col1", "Col2", "Col3"))
for row in matrix:
    print("{:>5} {:>5} {:>5}".format(*row))

Result:

 Col1 Col2 Col3
    1    2    3
    4    5    6
    7    8    9

Using f‑strings (Python 3.6+) achieves the same with slightly less boilerplate:

print(f"{'Col1':>5} {'Col2':>5} {'Col3':>5}")
for row in matrix:
    print(f"{row[0]:>5} {row[1]:>5} {row[2]:>5}")

Printing NumPy Arrays with set_printoptions

NumPy provides a dedicated configuration system for controlling how arrays appear. The function np.set_printoptions lets you adjust precision, threshold for summarizing large arrays, line width, and more Still holds up..

import numpy as np

big = np.random.rand(100, 100)   # a 100×100 matrix

# Default: NumPy truncates with "..."
print(big[:5, :5])               # shows only a corner

# Change threshold to show the whole array (use with caution for huge data)
np.set_printoptions(threshold=np.inf)
print(big)                       # prints the full 100×100 matrix

# Reset to default behavior
np.set_printoptions(threshold=1000)

Other useful options:

Option Effect
precision Number of decimal points shown for floating point values
linewidth Maximum characters per line before inserting a break
suppress If True, small floating‑point numbers are printed as 0
formatter A dictionary mapping dtype to a custom formatting function

Some disagree here. Fair enough Not complicated — just consistent..

Example with custom formatter:

np.set_printoptions(formatter={'float_kind': lambda x: f"{x:0.2f}"})
print(np.array([0.12345, 6.789]))
# Output: [0.12 6.79]

Printing Multi‑Dimensional Arrays

Both nested lists and NumPy arrays can represent matrices, tensors, or higher‑dimensional data. The approach you choose depends on readability and performance

For small, irregular, or heterogeneous collections, nested lists are often sufficient. They require no external dependencies, and pprint handles most nesting depths gracefully. That said, as the number of dimensions grows, the indentation can become overwhelming, and pure‑Python loops for formatting add overhead.

NumPy arrays, by contrast, store homogeneous data in contiguous memory, which makes them faster to iterate and easier to summarize. Instead of printing every element, you can inspect shape, dtype, and a representative slice:

import numpy as np

tensor = np.rand(4, 4, 4)
print(f"Shape: {tensor.So random. shape}, dtype: {tensor.

For finer control over the string representation without changing global settings, `np.array2string` is useful:

```python
print(np.array2string(tensor, precision=3, suppress_small=True, max_line_width=80))

When the goal is a

Hot Off the Press

Freshly Published

Cut from the Same Cloth

We Picked These for You

Thank you for reading about How To Print An Array In Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home