How do you sum a multidimensional array in python?

The closest was this one summing columns.

So I'll do something similar in my question:

Say I've a Python 2D list as below:

my_list =  [ [1,2,3,4],
             [2,4,5,6] ]

I can get the row totals with a list comprehension:

row_totals = [ sum[x] for x in my_list ]

In one line, how can I sum the entire 2d-array?

27

asked Feb 29, 2012 at 10:21

You can do as easy as

sum[map[sum, my_list]]

or alternatively

sum[sum[x] for x in my_list]]

and call it a day, if you don't expect more than 2 dimensions. Note that the first solution is most likely not the fastest [as in execution time] solution, due to the usage of map[]. Benchmark and compare as necessary.

Finally, if you find yourself using multidimensional arrays, consider using NumPy and its superior array-friendly functions. Here's a short excerpt for your problem:

import numpy as np

my_list = np.array[[[1,2,3,4], [2,4,5,6]]]
np.sum[my_list]

This would work for any number of dimensions your arrays might have.

answered Feb 29, 2012 at 10:36

mindcorrosivemindcorrosive

6961 gold badge7 silver badges13 bronze badges

5

Another solution using itertools:

>>> from itertools import chain
>>> my_list = [ [1,2,3,4], [2,4,5,6] ]
>>> sum[chain[*my_list]]
27

answered Feb 29, 2012 at 10:42

Tim PietzckerTim Pietzcker

318k56 gold badges494 silver badges550 bronze badges

2

>>> sum [ [ sum[x] for x in [[1,2,3,4], [2,4,5,6]] ] ]
27

answered Feb 29, 2012 at 10:32

CapelliCCapelliC

59k5 gold badges45 silver badges89 bronze badges

2

>>> from itertools import chain
>>> my_list = [[1,2,3,4], [2,4,5,6]]
>>> sum[chain.from_iterable[my_list]]
27

answered Feb 29, 2012 at 12:22

John La RooyJohn La Rooy

286k51 gold badges358 silver badges498 bronze badges

You can use sum to first add the inner lists together and then sum the resulting flattened list:

>>> my_list = [ [1,2,3,4], [2,4,5,6] ]

>>> sum[my_list, []]
[1, 2, 3, 4, 2, 4, 5, 6]

>>> sum[sum[my_list, []]]
27

answered Dec 26, 2015 at 2:43

HenryHenry

4576 silver badges16 bronze badges

1

For many languages such as Java and C++, arrays and lists are different objects. C++ doesn’t even technically have “lists” and Java has a hybrid object called an ArrayList. While there are arrays in Python, such as numpy arrays, Python’s most common sequence or series collection is a list object. 

Python list objects may contain entries of any type from numbers to strings to dictionaries, and may even contain multiple types. I’ll be using “array” and “list” interchangeably in this post because they are used in almost the exact same way in Python. In this post we’re going to cover how to sum a 2D list [or array] of numbers in Python. We’ll cover the following sections:

  • What is a 2D Array or List in Python
  • How Do You Sum an Array?
  • How Do You Sum a 2D List?
  • Summary of Summing a 2D Array in Python

What is a 2D Array or List in Python?

In many other languages, such as Java, you’d need to declare a 2D array type before assigning it. In Python, we can just make a list and make each entry in the list another list. A 2D array represents a two-dimensional space. These are sometimes referred to as “nested” lists. In our example, we’ll create a list of three lists, each consisting of two numbers. The below code shows how we can instantiate a simple 2D list in Python.

example_2d = [[1, 2], [3, 4], [5, 6]]

How Do You Sum an Array in Python?

There are multiple ways to sum a list in Python. We can do it iteratively, we can break the list down, or we can use the built-in sum[] method. In this post, we’re going to sum a list the simplest way, by using the sum[] method. In the example below we create a one-dimensional list of three numbers and then sum them.

example_1d =[1, 2, 3]
print[sum[example_1d]]

This should output 6.

How Do You Sum a 2D List in Python?

Summing a 2D list or array object in Python is much more difficult. You can’t call the sum[] function on a 2D array. If you try, you will get a TypeError of  unsupported operand type[s] for +: 'int' and 'list'. So, how can we sum a 2D array in Python? I’ll go over three examples here, first an iterative example, and then two Pythonic one liners.

Sum the 2D List with a For Loop

Summing a 2D array with a for loop is the most straightforward approach, especially for people new to Python. This is also the most intuitive approach for people coming from other programming languages. We start off with a sum of 0, notice that I named this variable _sum because the word sum is the name of the function. Then, we loop through each entry in the 2D list and add the sum[] of that entry to our _sum variable. Finally, we print out our _sum variable to make sure that we got it.

_sum=0
for x in example_2d:
    _sum += sum[x]
print[_sum]

This should print 21.

Pythonically Sum The 2D Array in One Line

Now let’s take a look at the first “Pythonic” way of summing a 2D array. We can do this in one line. The most “inner” function of our line will use list comprehension and create a list from the sums of each entry in the 2D list. Then, we’ll call sum[] on that and print it out. 

The inner list should be [3, 7, 11]. The printed answer should once again be 21.

print[sum[[sum[x] for x in example_2d]]]

Pythonically Sum the 2D List in One Line [More Obscure]

Finally, let’s take a look at another Pythonic way to sum a 2D array. We can take advantage of the sum[] function’s optional second parameter. Usually, sum[] expects to be summing numbers, so if you just call sum[] on a 2D list, you’ll get a TypeError as we saw earlier. However, the optional second start parameter allows us to bypass this. If we pass an empty list object, it will expect the individual entries of the 2D array to be list objects like they are. This allows us to then call sum[] again on the list and sum a 1D array.

The output of sum[example_2d, []] is [1, 2, 3, 4, 5, 6] just as if we added the lists together. The print statement prints 21.

print[sum[sum[example_2d, []]]]

Summary of How to Sum a 2D List or Array

In this post we went over what a 2D list is and how you can sum arrays in Python. We also went over three separate methods to sum 2D lists. First, we went over an iterative method using for loops. Then, we went over a classic Pythonic method. Finally, we went over a more obscure approach using the optional start parameter of the sum[] function.

Learn More

To learn more, feel free to reach out to me @yujian_tang on Twitter, connect with me on LinkedIn, and join our Discord. Remember to follow the blog to stay updated with cool Python projects and ways to level up your Software and Python skills! If you liked this article, please Tweet it, share it on LinkedIn, or tell your friends!

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

Or enter a custom amount

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

How do you find the sum of two multidimensional arrays?

Iterate through every number in the array [array length]..
Sum the objects of the same index in both of the arrays..
Push the sum into another array for the result. Use parseFloat if the input is string..
[Optional] use . toFixed[1] to set decimal place to have 1 digit..

How do you sum a two dimensional array in python?

In this tutorial, we are going to find the sum of a 2D array using map function in Python..
Initialize the 2D array using lists..
Pass the function sum and 2D array to the map function..
Find the sum of resultant map object and print it..

How do you sum an array value in python?

STEP 1: Declare and initialize an array..
STEP 2: The variable sum will be used to calculate the sum of the elements. Initialize it to 0..
STEP 3: Loop through the array and add each element of the array to the variable sum as sum = sum + arr[i]..

How do you sum the elements of an array in NumPy?

sum[] in Python. The numpy. sum[] function is available in the NumPy package of Python. This function is used to compute the sum of all elements, the sum of each row, and the sum of each column of a given array.

Chủ Đề