Note that this tutorial concerns NumPy arrays. To learn how to print lists without brackets check out this tutorial:
Given a NumPy array of elements. If you print the array to the shell using
print(np.array([1, 2, 3])), the output is enclosed in square brackets like so:
[1 2 3]. But you want the array without brackets like so:
1 2 3.
import numpy as np my_array = np.array([1, 2, 3]) print(my_array) # Output: [1 2 3] # Desired: 1 2 3
How to print the array without enclosing brackets?
Method 1: Unpacking 1D Arrays
The asterisk operator
* is used to unpack an iterable into the argument list of a given function. You can unpack all array elements into the
print() function to print each of them individually. Per default, all print arguments are separated by an empty space. For example, the expression
print(*my_array) will print the elements in
my_array, empty-space separated, without the enclosing square brackets!
import numpy as np my_array = np.array([1, 2, 3]) print(*my_array) # Output: 1 2 3
To master the basics of unpacking, feel free to check out this video on the asterisk operator:
Method 2: Unpacking with Separator for 1D Arrays
To print a NumPy array without enclosing square brackets, the most Pythonic way is to unpack all array values into the
print() function and use the
sep=', ' argument to separate the array elements with a comma and a space. Specifically, the expression
print(*my_array, sep=', ') will print the array elements without brackets and with a comma between subsequent elements.
import numpy as np my_array = np.array([1, 2, 3]) print(*my_array, sep=', ') # Output: 1, 2, 3
Note that this solution and the previous solution work on 1D arrays. If you apply it to arrays with more dimensions, you’ll realize that it only removes the outermost square brackets:
import numpy as np my_array = np.array([[1, 2, 3], [4, 5, 6]]) print(*my_array, sep=', ') # Output: [1 2 3], [4 5 6]
You can learn about the ins and outs of the built-in
print() function in the following video:
Method 3: Print 2D Arrays Without Brackets
To print a 2D NumPy array without any inner or outer enclosing square brackets, the most simple way is to remove all square bracket characters. You can do this with the
string.replace() method that returns a new string by replacing the square bracket characters
']' with the empty string. To avoid bad indentation, we chain three replacing operations, first replacing the empty space followed by the opening bracket like so:
print(str(my_array).replace(' [', '').replace('[', '').replace(']', '')).
import numpy as np my_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(str(my_array).replace(' [', '').replace('[', '').replace(']', ''))
The output is the 2D NumPy array without square brackets:
1 2 3 4 5 6 7 8 9
Feel free to dive deeper into the string replacement method in this video:
Method 4: Regex Sub Method
You can use the
regex.sub(pattern, '', string) method to create a new string with all occurrences of a pattern removed from the original string. If you apply it to the string representation of a NumPy array and pass the pattern
'( \[|\[|\])' with escaped brackets to avoid their special meaning (character set), you’ll remove all enclosing square brackets from the output.
import numpy as np import re my_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(re.sub('( \[|\[|\])', '', str(my_array)))
The output is:
1 2 3 4 5 6 7 8 9
import numpy as np import re my_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(re.sub(' ?[\[\]]', '', str(my_array)))
You can check out my full tutorial on regular expressions if you need a complete guide, or you just watch the regex sub video here:
Method 5: Python One-Liner
To print a NumPy array without brackets, you can also generate a list of strings using list comprehension, each being a row without square bracket using slicing
str(row)[1:-1] to skip the leading and trailing bracket characters. The resulting list of strings can be unpacked into the
print() function using the newline character
'\n' as a separator between the strings.
import numpy as np my_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(*[str(row)[1:-1] for row in my_array], sep='\n')
The output is:
1 2 3 4 5 6 7 8 9
Feel free to dive into slicing next to boost your coding skills:
If you want to master the Python one-liner superpower too, check out my book! 🙂
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.