How to print element in an array

Published on Aug. 22, 2023, 12:16 p.m.

To print elements in an array in Python, you can use a loop to iterate through the array and print each element. Here’s an example:

my_array = [1, 2, 3, 4, 5]

for element in my_array:
    print(element)

In this code, we define an array called my_array containing some integer elements. We then use a for loop to iterate through each element of the array, and use the print() function to print out each element.

Alternatively, you can also use the join() method to concatenate all the elements into a string and then print the string. Here’s an example:

my_array = [1, 2, 3, 4, 5]
array_str = ', '.join(str(element) for element in my_array)

print("Elements in the array:", array_str)

In this code, we define an array called my_array containing some integer elements. We then use a generator expression and the join() method to concatenate all the elements into a comma-separated string. Finally, we print out the string using the print() function.

Note that these examples assume that you have a simple one-dimensional array. If you have a multidimensional array or a more complex data structure, you may need to use nested loops or other techniques to access and print each element.

use the pprint module in Python

You can use the pprint module in Python to print an array in a nicely formatted way. pprint stands for “pretty-print,” and it provides a way to print out nested data structures, such as arrays and dictionaries, in a way that makes it easier to read. Here is an example:

import pprint

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

pprint.pprint(my_array)

In this code, we first import the pprint module. We then define our array called my_array, which contains three sub-arrays. We use the pprint.pprint() function to print out the array in a nicely formatted way.

The output of this code will look something like:

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

As you can see, each sub-array is printed on a separate line, and the elements of each sub-array are aligned in columns.

Note that the pprint module is especially useful when dealing with large and complex nested data structures, as it can help make sense of the structure and relationships between the various elements.

Tags:

related content