2D List (row total/grand total) in Python

python sum columns of 2d array
sum of rows in array java
sum of rows and columns in 2d array in c
empty 2d list python
row sum and column sum of a matrix in c++
sum of elements in 2d array in c++
sum of elements in 2d array java
we pass in 2 numbers, a and b. you should create a list with a rows and b columns.

My question is about obtaining the sum of each row in a 2d list and then obtaining the total of all rows. Below is the information given to me--

We will pass in a 2 dimensional list of numbers. You should:

*add up all the numbers in each row and output that number

*output the grand total of all rows

this is the code given to me:

# Get our list from the command line arguments
import sys
numbers= sys.argv[1:]

# Convert the command line arguments into 2d list
for i in range(0,len(numbers)): 
    numbers[i]= numbers[i].split(',')

This work is completed via Codio. When I print my 2d list this is the output I get:

print(numbers)
[['1', '1', '-2'], ['-1', '-2', '-3'], ['1', '1', '1']]

Based on previous problems and scenarios I have worked, these numbers have changed based on the coding I have developed to make sure it meets all the guidelines of the assignment.

I have tried various attempts at the problem, listed below:

row = len(numbers)
column = len(numbers[0])
total = 0

for row in numbers:
    rowtotal = 0
    for column in numbers:
        rowtotal = rowtotal + numbers[row][column]
        print(rowtotal)
        total = total + rowtotal
print(total)

This gives the error:

Traceback (most recent call last):
  File "list.py", line 17, in 
    rowtotal = rowtotal + numbers[row][column]
TypeError: list indices must be integers, not list

I have also tried:

row = len(numbers)
column = len(numbers[0])
total = 0

for row in range (len(numbers)):
    for col in range(len(numbers[0])):
        total = total + numbers[row][column]
print(total)

Which gives me the error:

Traceback (most recent call last):
  File "list.py", line 16, in 
    total = total + numbers[row][column]
IndexError: list index out of range

For my last attempt I tried:

total = 0
for x in range (0, len(numbers)):
    rowtotal = 0
    for y in range (0, len(numbers[0])):
        rowtotal = rowtotal = int(numbers[x][y])
    print(rowtotal)
    total = total + rowtotal
print(total)

Which finally gave me numbers, but not the correct ones:

Program Failed for Input: 1,1,-2 -1,-2,-3 1,1,1
Expected Output: 0
-6
 3
-3
Your Program Output: -2
-3
 1
-4

If I could get any help I would be greatly appreciative.

I think it's instructional to break down your attempts one by one and talk about what went wrong in each one.

For starters, your input list is a 2-dimensional list of numbers as strings. You'll need to cast them to int, preferably right off the bat. However, I'll assume the input list you're working with in your code is the following:

[['1', '1', '-2'], ['-1', '-2', '-3'], ['1', '1', '1']]

which needs its elements to be cast to int to avoid crashing.


Attempt 1

Your code:

row = len(numbers)
column = len(numbers[0])
total = 0

for row in numbers:
    rowtotal = 0
    for column in numbers: # <-- are these really columns as advertised or still rows?
        rowtotal = rowtotal + numbers[row][column] # <-- crash!
        print(rowtotal)
        total = total + rowtotal # <-- are you sure you want to do this here?
print(total)

The primary misunderstanding is that your statement for row in numbers: loops through the actual lists in the numbers list, not the indices of this list. In other words, row is equal to ['1', '1', '-2'] on the first iteration, not 0.

Similarly, for column in numbers: is mis-labeled and also iterates over row lists rather than the intended cells in rows. The crash happens when you try to index into the list numbers using these items. Your code is doing:

numbers[['1', '1', '-2']][['1', '1', '-2']] # crash

You can fix this by not attempting to index into the numbers list, but instead using the row and column elements to compute the total.

You also have a logic error that prematurely adds rowtotal to the aggregate total, which over counts.

Lastly, the first two lines do nothing because the values are overwritten by the loop variables; remove them.

Here's a re-write:

total = 0

for row in numbers:
    rowtotal = 0

    for column in row: # <-- iterating cells in rows
        rowtotal = rowtotal + int(column) # <-- much better

    total = total + rowtotal # <-- logic error fixed

print(total)

Attempt 2

Your code:

row = len(numbers)
column = len(numbers[0])
total = 0

for row in range (len(numbers)):
    for col in range(len(numbers[0])):
        total = total + numbers[row][column] # <-- crash!
print(total)

Similar problem here as the first. You have two lines at the beginning that introduce the variables row and column. When you write for row in range(len(numbers)): you overwrite the row variable you initialized on line 1.

However, when you write for col in range(len(numbers[0])):, you don't overwrite column and you attempt to index into numbers using the out of bounds column variable, which stores the length of the list, crashing the program.

Of course, don't forget to cast to int if you haven't already done so.

Fixed:

total = 0

for row in range(len(numbers)):
    for col in range(len(numbers[row])): # added row here in case of a ragged list
        total += int(numbers[row][col])

print(total)

Attempt 3

Your code:

total = 0
for x in range (0, len(numbers)):
    rowtotal = 0
    for y in range (0, len(numbers[0])):
        rowtotal = rowtotal = int(numbers[x][y]) # <-- typo! = should be +
    print(rowtotal)
    total = total + rowtotal
print(total)

So close! The issue here is that you've used the wrong operator, = when you meant +. I recommend using the += operator going forward, which adds the right hand side expression to the left hand side variable and stores it in the left hand side variable.

Fixed:

total = 0

for x in range (0, len(numbers)):
    rowtotal = 0

    for y in range (0, len(numbers[0])):
        rowtotal = rowtotal + int(numbers[x][y]) # or use rowtotal += int(numbers[x][y])

    total += rowtotal

print(total)

My version

Here's how I'd write this:

print(sum([sum([int(n) for n in row]) for row in numbers]))

This uses something called a list comprehension, which is basically a one-line for loop that creates a list.

As pointed out by @jpp,

print(sum([sum(map(int, row)) for row in numbers]))

is even shorter, using the map function to apply the int cast to every element of row.

Don't stress if these are confusing--the important part is learning how to debug your existing programs, which is all about evaluating your assumptions step by step and walking through your logic in small chunks. When you have a crash and a printed stack trace, that's good--it tells you exactly what went wrong and where to look. If that still doesn't make the situation clear, simplify your code to a point where it works and you understand your program state, then build up again.

Here's a repl to play around with all of the working solutions.

addition of rows and grand total in 2d lists python, Since you only want help being directed and not have a full answer, here is what you should do : Identify your data. Find similiarities, ways to  A two-dimensional list is really nothing more than an list of lists (a three-dimensional list is a list of lists of lists). Think of your dinner. You could have a one-dimensional list of everything you eat: (lettuce, tomatoes, salad dressing, steak, mashed potatoes, string beans, cake, ice cream, coffee)

I am new to the site so I wasn't able to comment on the users answer that was marked as accepted but I noticed an issue in the code. It was only outputting one part of the question that was asked. The original code was:

total = 0

for row in numbers:
    rowtotal = 0

   for column in row:  
       rowtotal = rowtotal + int(column) 

total = total + rowtotal  

print(total)

But it also needed to print the "rowtotal" so the answer to the question would be one more line of code like this:

total = 0

for row in numbers:
    rowtotal = 0

   for column in row: 
       rowtotal = rowtotal + int(column) 
   print(rowtotal) # <---- New line of code
total = total + rowtotal 

print(total)

Now it would be able to pass in your Codio environment as both outputs would print.1) the total of each row and 2) the grand total of all rows. I hope this is helpful to anyone who is also using the Codio IDE for their classes and come across this challenge. As always there is ways to simplify the code, but if your at this stage in your course it is probably beyond the scope that you have reached.

Adding and printing lists in python - Random, This 2d list code works with lists of the same length but it one list has a shorter index it does not work. But it work when the total=0 for x in range(0, rows): rowtotal=0 for y in range(0, cols): •output the grand total of all rows. and then it will convert this into a 2d list, so in our example, numbers would be: So the problem is now reduced to getting the total sum of all the numbers (1+2+3+4+5+6+7+8+9). This can be done in one line: which gives us the expected output of 45.

You can leverage python list comprehension and the built-in sum function to do this quite easily:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
row_totals = [sum(row) for row in matrix]
grand_total = sum(row_totals)

Or, you could use vanilla loops and addition:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
row_totals = []
grand_total = 0
for row in matrix:
    row_total = 0
    for value in row:
        row_total += value
    row_totals.append(row_total)
    grand_total += row_total

Program to find the Sum of each Row and each Column of a Matrix , Program to reverse the rows in a 2d Array · Minimum cost to reach from the top-​left Given a matrix of order m*n, the task is to find out the sum of each row and each Input: array[4][4] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; Output: Sum of the Python 3. filter_none. edit close. play_arrow. link brightness_4 code​  2. A single 1d list is created and all its indices point to the same int object in point 1. 3. Now, arr[0], arr[1], arr[2] …. arr[n-1] all point to the same list object above in point 2. The above setup can be visualized in the image below. Now lets change the first element in first row of “arr” as arr[0][0] = 1

2d Lists, Creating 2d Lists; Getting 2d List Dimensions; Copying and Aliasing 2d Lists; Printing 2d Try, and FAIL, to create a variable-sized 2d list rows = 3 cols = 2 a = [ [0] * cols ] * rows len(str(a[row][col]))) return maxLen # Because Python prints 2d lists on one row, # we Accessing a whole column with a list comprehension. Chapter 9: Hello totals¶ In some ways, your database is no different from a human source. Getting a good story requires careful, thorough questioning. In this section we will move ahead by conducting an interview with pandas to pursue our quest of finding out the biggest donors to Proposition 64.

Solved: Python Challenge Question We Will Pass In A 2 Dime , Answer to Python Challenge Question We will pass in a 2 dimensional list of numbers. You Should Add Up All The Numbers In Each Row And Output That Number Output The Grand Total Convert the command line arguments into 2d list It'd be great to not have to calculate the total outside of the pivot tabe and just be able to call the Grand Total from the first pivot. But even if I have to calculate separately, like in the code above, as long as it adds up to 100% it would still be great. Thank you in advance!

How to sum rows and columns in a 2d list? : learnpython, r/learnpython: Subreddit for posting questions and asking for general advice about your python code. In real-world Often tasks have to store rectangular data table. [say more on this!] Such tables are called matrices or two-dimensional arrays. In Python any table can be represented as a list of lists (a list, where each element is in turn a list). For example, here's the program that creates a numerical table with two rows and three columns

Comments
  • On your second attempt, in total = total + numbers[row][column] change column for col. And convert the numbers (that are str, you can't sum a int with a str) to int. Something like total = total + int(numbers[row][col])
  • sum(map(int, row)) better imo. No need to feed a list to sum.
  • Good call. I forget about map.
  • You can also get rid of the square brackets and use a generator expression.
  • Thank you so much! I used my attempt 1 with the information you provided, it passed :)
  • @jpp We haven't used map in our studies yet so I don't really feel comfortable using that technique yet, but thank you for the suggestion
  • I get the below error when I use the loop example you have provided: Traceback (most recent call last): File "list.py", line 16, in row_total += value TypeError: unsupported operand type(s) for +=: 'int' and 'str'
  • If the items in the list are strings and not integers, then you need to cast them to integers first, using int(value)