Learn how to print a 2D array in Python without displaying the brackets and quotes. This guide provides simple solutions for cleaner array outputs.
---
Disclaimer/Disclosure: Some of the content was synthetically produced using various Generative AI (artificial intelligence) tools; so, there may be inaccuracies or misleading information present in the video. Please consider this before relying on the content to make any decisions or take any actions etc. If you still have any concerns, please feel free to write them in a comment. Thank you.
---
How to Print a 2D Array in Python Without Brackets and Quotes
When working with 2D arrays in Python, you might sometimes want to print the array in a more readable format, without the brackets and quotes that usually come with lists of lists. While Python's default output for lists includes these characters, there are simple ways to get around them.
Using Nested Loops
One of the most straightforward methods is to use nested loops. Here’s how you can do it:
[[See Video to Reveal this Text or Code Snippet]]
Explanation
The outer loop iterates over each row in the 2D array.
The inner loop iterates over each element in the row.
The print(elem, end=' ') statement prints the element followed by a space, without a newline.
The print() statement after the inner loop ensures that a newline is printed after each row.
Using List Comprehension and Join
Another efficient way to get a clean print is by using list comprehension and the join method:
[[See Video to Reveal this Text or Code Snippet]]
Explanation
The map(str, row) function converts each element in the row to a string.
The ' '.join() method combines these strings with a space in between.
Each row is printed cleanly without brackets or quotes.
Custom Formatter Function
For more complex requirements, you can encapsulate the printing logic in a custom formatter function:
[[See Video to Reveal this Text or Code Snippet]]
Explanation
Define a function print_2d_array that takes a 2D array as a parameter.
Inside the function, iterate over each row and format it using the join method.
Print each formatted row.
By using any of the above methods, you can print your 2D arrays in Python without the clutter of brackets and quotes, making the output cleaner and easier to read.
On this page of the site you can watch the video online How to Print a 2D Array in Python Without Brackets and Quotes with a duration of hours minute second in good quality, which was uploaded by the user vlogize 20 January 2025, share the link with friends and acquaintances, this video has already been watched 11 times on youtube and it was liked by like viewers. Enjoy your viewing!