# Summing a 2D Array in Python

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.

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.

Yujian Tang

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!

One-Time
Monthly
Yearly

#### Make a yearly donation

Choose an amount

\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00

Or enter a custom amount

\$

## 4 thoughts on “Summing a 2D Array in Python”

1. Gerald Osterman - can you help with my error in the 5th line from the end? says:

”’
Odd Man wins, Problem 4
odd man wins one penny from each of the
other two players, thus winner gets 2 cents,
losers each lose only one cent, how many flips
on average until someone goes out?
”’
#import Counter
import random
flip_count = 0
run_count = 0

for run_count in range(0, 5):
l = 1 #beginning coins of the 3 players
m = 1
n = 1

flip_count = 0

for x in range(1, 10):
flip1 = random.randint(0,1)
flip2 = random.randint(0,1)
flip3 = random.randint(0,1)
set = flip1, flip2, flip3
set_tot = (flip1+flip2+flip3)
if set_tot == 0:
l = l
m = m
n = n
if set_tot == 3:
l = l
m = m
n = n
if set_tot == 1:
if flip1 == 1:
l = l+2
else:
l = l-1
if flip2 == 1:
m = m+2
else:
m = m-1
if flip3 == 1:
n = n+2
else:
n = n-1
if set_tot == 2:
if flip1 == 0:
l = l+2
else:
l = l-1
if flip2 == 0:
m = m+2
else:
m = m-1
if flip3 == 0:
n = n+2
else:
n = n-1

flip_count += 1

print(set, set_tot)
print(‘{0}, {1}, {2}’.format(l,m,n))

if l==0 or m==0 or n==0:
break

print(‘The flip count is: {0}’.format(flip_count))

flip_count = flip_count + 1 #error here, its adding 1 to the last individual flip count
run_count = run_count + 1
print(‘The run count is: {0}’.format(run_count))
print(‘The overall flip count is: {0}’.format(flip_count))
print(‘Average Flips/Runs = : {0}’.format(flip_count/run_count))

2. Gerald Osterman says:

Neve rmind, I figured it out and it works now:
”’
“Digital Dice”, Problem 4,
odd man wins one penny from each of the
other two players, thus winner gets 2 cents,
losers each lose only one cent, how many flips
on average until someone goes out?
”’

import random
flip_ct_tot = 0
run_count = 0

for run_count in range(0, 100):
l = 1 #beginning coins of the 3 players
m = 1
n = 1

flip_count = 0

for x in range(1, 10):
flip1 = random.randint(0,1)
flip2 = random.randint(0,1)
flip3 = random.randint(0,1)
set = flip1, flip2, flip3
set_tot = (flip1+flip2+flip3)
if set_tot == 0:
l = l
m = m
n = n
if set_tot == 3:
l = l
m = m
n = n
if set_tot == 1:
if flip1 == 1:
l = l+2
else:
l = l-1
if flip2 == 1:
m = m+2
else:
m = m-1
if flip3 == 1:
n = n+2
else:
n = n-1
if set_tot == 2:
if flip1 == 0:
l = l+2
else:
l = l-1
if flip2 == 0:
m = m+2
else:
m = m-1
if flip3 == 0:
n = n+2
else:
n = n-1

flip_count += 1
flip_ct_tot += 1
print(set, set_tot)
print(‘{0}, {1}, {2}’.format(l,m,n))

if l==0 or m==0 or n==0:
break

print(‘The flip count is: {0}’.format(flip_count))

run_count = run_count + 1
print(‘The run count is: {0}’.format(run_count))
print(‘The overall flip count is: {0}’.format(flip_ct_tot))
print(‘Average Flips/Runs = : {0}’.format(flip_ct_tot/run_count))

1. Yujian Tang says:

nice! that was quick of your to figure out!