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
JavaScript
x
8
1
D=[[12,10,13,14,13,-2,17,20,19,14],[9,-5,11,20,10,16,13,22,15,12]]
2
3
# Replace negative values in demand list by 0
4
for i in D:
5
for j in i:
6
if i[j] < 0:
7
D[i][j] = 0
8
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):
JavaScript
1
5
1
for i in D:
2
for j in range(len(i)):
3
if i[j] < 0:
4
i[j] = 0
5
Alternatively, you can use a list comprehension:
JavaScript
1
2
1
D = [[x if x >= 0 else 0 for x in d] for d in D]
2