3 ways to print an array in Python:
- Direct Printing
- Using for loop
- Pretty Printing
Method 1: Direct Printing
The print() function takes the name of the array(list) containing the values and prints it.
Visual Representation
Example 1: Array(list)
even_array = [2, 4, 6, 8, 10]
even_2d_array = [[2, 4], [6, 8]]
print("Printing 1D array:", even_array)
print("Printing 2D array:", even_2d_array)
Output
Printing 1D array: [2, 4, 6, 8, 10]
Printing 2D array: [[2, 4], [6, 8]]
Example 2: NumPy Array
You can create a NumPy array using the np.array() function.
import numpy as np
odd_array = np.array([1, 3, 5, 7, 9])
odd_2d_array = np.array([[1, 3], [5, 7]])
print("Printing 1D NumPy array:", odd_array)
print("Printing 2D NumPy array:", odd_2d_array)
Output
Printing 1D array: [1 3 5 7 9]
Printing 2D array:
[[1 3]
[5 7]]
Method 2: Using for loop
To print the elements of an array line by line or with a custom format, you can use a for loop.
For a 1D array, the loop iterates through each element, printing them one by one.
For a 2D (multidimensional) array, a nested for loop is used: the outer loop iterates through each row, while the inner loop handles each element within that row, enabling the printing of the array in a matrix-like format.
Example 1: Array(list)
even_array = [2, 4, 6, 8, 10]
even_2d_array = [[2, 4], [6, 8]]
print("Printing 1D array : ")
for element in even_array:
print(element)
print("Printing 2D array : ")
for row in even_2d_array:
for x in row:
print(x, end=" ")
print()
Output
Printing 1D array :
2
4
6
8
10
Printing 2D array :
2 4
6 8
Example 2: NumPy Array
import numpy as np
odd_array = np.array([1, 3, 5, 7, 9])
odd_2d_array = np.array([[1, 3], [5, 7]])
print("Printing 1D NumPy array: ")
for element in odd_array:
print(element)
print("Printing 2D NumPy array:")
for row in odd_2d_array:
for x in row:
print(x, end=" ")
print()
Output
Printing 1D NumPy array:
1
3
5
7
9
Printing 2D NumPy array:
1 3
5 7
Method 3: Pretty Printing
The pprint module can be useful for nested arrays or arrays with complex data structures.
It is used with an indent parameter to specify the number of spaces for indentation.
Example
import pprint
nested_array = [
[1, 2, 3, 4, 5],
[6, 7, 8],
[9, 10, 11, 12, 13, 14],
['a', 'b', 'c', ['d', 'e', 'f', ['g', 'h']]]
]
# Using pprint to print the nested array
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(nested_array)
Output
[ [1, 2, 3, 4, 5],
[6, 7, 8],
[9, 10, 11, 12, 13, 14],
['a', 'b', 'c', ['d', 'e', 'f', ['g', 'h']]]]
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.