Sush R Sush R - 1 year ago 63
Python Question

Why do I get a 'list index out of range' error for the below code using a for loop:

Problem Statement: Given a nested list nl consisting of a set of integers, write a python script to find the sum of alternate elements of the sub-lists.

nl = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
sum = 0
n = 0
for ele in nl:
for i in ele:
for a in j:
sum = sum + j[n]
n = n + 2

When I run this code, I get an error:

Traceback (most recent call last):
File "C:\Users\ARUDRAVA\Contacts\Desktop\lists Assigment\",line 14, in <module>
sum = sum + j[n]
IndexError: list index out of range

Why is this error generated?

Answer Source

This is how it's usually done in Python:

nl =  [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

total = sum(number for sublist in nl for number in sublist)

Don't name the variable sum - that would "hide" a built-in function. Exactly the function you need in fact.

Anyway, the error in your code was here:

sum = sum + j[n]

It should have been:

sum = sum + a
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download