Skip to content
Advertisement

loop in a list of lists

I am trying to use two foor loops for a variable with that has list within a list, but this code doesn’t work. I get the error: list index out of range

D=[[12,10,13,14,13,-2,17,20,19,14],[9,-5,11,20,10,16,13,22,15,12]]

  # Replace negative values in demand list by 0
    for i in D:
        for j in i:
            if i[j] < 0:
                D[i][j] = 0

Advertisement

Answer

In your loop, j is not an index, it’s the element, you can use range to loop over the indices (same thing about i, use i[j], not D[i][j], since i is a list):

for i in D:
    for j in range(len(i)):
        if i[j] < 0:
            i[j] = 0

Alternatively, you can use a list comprehension:

D = [[x if x >= 0 else 0 for x in d] for d in D]
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement