简体   繁体   中英

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
j=[]
for ele in nl:
    for i in ele:
        j.append(i)
        for a in j:
            sum = sum + j[n]
            n = n + 2
print(sum)

When I run this code, I get an error:

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

Why is this error generated?

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

Your outer loops look like this:

for ele in nl:
    for i in ele:
        j.append(i)
        # inner loop.

The first time the inner loop is reached, only one element has been appended to the list j . The second time the inner loop is reached, two elements have been appended to j , so the second time the loop is reached, j is [1,2] .

It seems from your comment that you think that when the inner loop is reached, that j contains all 12 numbers from nl . That's not correct. Perhaps you meant for the "inner loop" to come after the two outside loops and not inside them.

Let's it is the second time that the inner loop is reached j=[1,2] , and suppose n=0 (it might be larger than this but it can't be smaller)

Let's check the inner loop

    for a in j:
        sum = sum + j[n]
        n = n + 2

Because j has two elements, it will loop twice:

The first time through the loop it adds j[0] to sum, and sets n=0+2

The second time through the loop it tries to add j[2] to sum, which is a IndexError.

You will need to rethink the logic of your program. Good Luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM