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.

rows = len(numbers)
cols = len(numbers[0])
for x in range(0, rows):
for y in range(0, cols):

Error: RESTART: C:\Users\semcl\Documents\SNHU\Classes\IT140_IntroToScripting\PythonExamples\
Traceback (most recent call last):
File “C:\Users\semcl\Documents\SNHU\Classes\IT140_IntroToScripting\PythonExamples\”, 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.