Adding and printing lists in python

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 indexes are the same length.

numbers=[[1,2,3],[4,6],[7,8,9],[10,11,12]]
rows = len(numbers)
cols = len(numbers[0])
total=0
for x in range(0, rows):
rowtotal=0
for y in range(0, cols):
rowtotal=rowtotal+int(numbers[x][y])
print(rowtotal)
total=total+rowtotal
print(total)

Error: RESTART: C:\Users\semcl\Documents\SNHU\Classes\IT140_IntroToScripting\PythonExamples\listEmOut4.py
Traceback (most recent call last):
File “C:\Users\semcl\Documents\SNHU\Classes\IT140_IntroToScripting\PythonExamples\listEmOut4.py”, line 5, in
for x in rows:
TypeError: ‘int’ object is not iterable

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

We cannot assume that each contained list is the same length, so that value should be derived from each iteration of the container list or not considered at all.

for x in numbers:       # read only, length is not a concern
    for number in x:    # again, read-only, no length concern

Note that x is a single inner list, and number is a digit in the inner list.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.