So I want to make this so I can check if another code is working, but I keep getting this error:
'list index out of range'
For the following code:
for L1[i] in range(0, len(L1)):
if L1[i]==L2[i]:
L1[i]='ok'
What is going wrong?
Assuming this is Python, there are two problems:
i
in the beginning of the for
-loop.L2
may not have as many items as L1
.for i in range(0, len(L1)):
try:
if L1[i] == L2[i]:
L1[i] = 'ok'
except IndexError:
break
As Frederik points out, you could use enumerate
as well:
for i, l1 in enumerate(L1):
try:
if L[i] == L2[i]:
L1[i] = 'ok'
except:
break
In my opinion, the increase in readability of enumerate
over range
is mostly offset by defining an extra variable (l1
) which you never use. But it is just my opinion.
One last option, which may be best, is to use zip
to merge the two lists (zip
truncates the longer of the two):
for i, l1, l2 in enumerate( zip(L1, L2) ):
if l1 == l2:
L1[i] = 'ok'