Solved: sum 2d array in python

The main problem related to summing a 2D array in Python is that the syntax for doing so can be quite complex and difficult to understand. This is because there are multiple ways of summing a 2D array, depending on the shape of the array and what type of summation is desired. For example, if you want to sum all elements in a 2D array, you would need to use nested for loops. If you want to sum only certain elements in a 2D array, then you would need to use list comprehensions or other more advanced techniques. Additionally, it can be difficult to debug errors when working with 2D arrays since they are more complex than 1D arrays.

def sum_2d_array(arr): 
    result = 0
    # iterate through rows 
    for i in range(0, len(arr)): 
        # iterate through columns 
        for j in range(0, len(arr[i])): 
            result += arr[i][j] 

    return result

# This code defines a function called sum_2d_array which takes in an array as an argument.
# The result variable is initialized to 0.
# A for loop is used to iterate through the rows of the array, and a nested for loop is used to iterate through the columns of each row.
# For each element in the array, its value is added to the result variable.
# Finally, the function returns the total sum of all elements in the array.

What is an array


An array in Python is a data structure that stores a collection of items. It is similar to a list, but the items stored in an array are typically of the same type and are accessed using numerical indices. Arrays can be used to store numbers, strings, objects, and other data types. They are also useful for performing mathematical operations on large sets of data.

Array vs List in Python

Array and List are both data structures in Python that are used to store collections of data. An Array is a data structure that stores items of the same type, while a List is a more flexible data structure that can store items of different types.

Arrays are faster and more efficient for storing and accessing data than Lists, but they are limited in their flexibility because all elements must be of the same type. Lists on the other hand, can contain elements of different types, but they take up more memory and are slower to access than Arrays.

How to sum a 2d array in Python

To sum a 2d array in Python, you can use the built-in sum() function. The syntax for this is as follows:

sum(array, axis=None)

Where array is the 2d array you want to sum and axis is an optional argument that specifies which axis of the array should be summed. If no value is given for axis, then all elements of the array will be summed.

For example, if we have a 2d array called my_array with 3 rows and 4 columns:


We can use the following code to sum all elements of my_array:

total = sum(my_array) #total = 78

Or we can use the following code to sum each row of my_array:

row_sums = sum(my_array ,axis=1) #row_sums = [10 26 42]

Related posts:

Leave a Comment