Print NumPy array without commas in Python

This post will print an array without any commas in Python. We will be tackling this problem with the help of loops. To be more specific we are going to use For loop. For loop iterates through each element one by one and prints it. We are using the same technique.

Code: using for loop

import numpy as np

array = np.array([1, 2, 3])
for _ in np.nditer(array):
    print(_, end=' ')
  1. In the example above, we input a list of all the items.
  2. We use for loop so that it transverses through each element one by one.
  3. We are printing the end result.

Output:

1 2 3

Using numpy.numarray.flatten()

We can use this function given in python to print the way we want our NumPy array to be published. This can be done as:

import numpy as np

array = np.array([[7, 6, 1], [4, 12, 6]])
print(" ".join(map(str, array.flatten())))

Explanation:

In the above example, we want to print our 2D NumPy Array into a string of numbers without commas and this can be done by using numpy.numarray.flatten(). The flatten() returns the NumPy array as it is. The .join(map(str, array...)) prints Numpy array without the comma.

Output:

7 6 1 4 12 6

With this example, we have completed our tutorial on printing NumPy array without commas.

Also read: How to add space after dot or comma in Python string

Leave a Reply

Your email address will not be published. Required fields are marked *