How to Count the Number of Elements in a Two-Dimensional Array in Python?

Estimated read time 1 min read

To count the number of elements in a two-dimensional array in Python, you can use a nested loop to iterate over each element in the array and increment a counter variable for each element.

Here’s an example:

# create a sample two-dimensional array
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# initialize a counter variable
count = 0

# iterate over each element in the array
for row in arr:
    for element in row:
        count += 1

print(f'The two-dimensional array contains {count} elements.')

In this example, we create a sample two-dimensional array with three rows and three columns. We then initialize a counter variable to zero and use a nested loop to iterate over each element in the array. For each element, we increment the counter variable by one.

Finally, we print a message to the console indicating the number of elements in the two-dimensional array. The output will be:

The two-dimensional array contains 9 elements.

Note that this approach assumes that the two-dimensional array is rectangular (i.e., all rows have the same number of columns). If the array is not rectangular, you will need to modify the loop to handle each row separately.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply