Suppose I have the following list of nested lists named val.
This is the original code:
val = [[63, 59, 47], 54, [59, 54, 47], [66, 59, 54], [65, 61]]
a = []
for i in range(len(val) - 1):
#multiple notes at the same time
try:
if len(val[i]) > 1:
for j in val[i]:
if len(val[i 1]) > 1:
#multiple to multiple
print(val[i 1])
for k in val[i 1]:
print(k)
except:
print('not importent')
Result:
not importent
not importent
[66, 59, 54]
66
59
54
[66, 59, 54]
66
59
54
[66, 59, 54]
66
59
54
[65, 61]
65
61
[65, 61]
65
61
[65, 61]
65
61
What I found interesting is that if I add other operations like a[0] = 1 after print(k) in the try block, print(k) is only executed once, and not printing integers exhaustively
val = [[63, 59, 47], 54, [59, 54, 47], [66, 59, 54], [65, 61]]
a = []
for i in range(len(val) - 1):
#multiple dots at the same time
try:
if len(val[i]) > 1:
for j in val[i]:
if isinstance(val[i 1],int):
#multiple to one
print('single value')
elif len(val[i 1]) > 1:
#multiple to multiple
print(val[i 1])
for k in val[i 1]:
print(k)
a[0] = 1
except:
print('not importent')
Result
not importent
not importent
[66, 59, 54]
66
not importent
[65, 61]
65
not importent
Can anybody explain why this happens? and how can I make the for loop complete even if I add more operations after print(k)?
CodePudding user response:
List a is initiated but no where it appended any of the value; but you're trying to assign a value in particular index which is not the correct way to do in Python.
Hence, it throws you an list index out of range
The problem is here,
a[0] = 1
so what you could have done to debug this issue is you should remove the try/ catch. Once you figure out the issue, again put your code inside the try/catch block.
Happy coding ..!