List Index Out Of Range : PYTHON - python

Even though I am getting valid Prints but still I am getting List Index out of range. The list where I am getting "Out of Range" error is "lstSHADOW_LOG_TABLE"
if((int(len(lstSHADOW_LOG_TABLE[index_shadow_log][1]))) > 1):
print("Length={0} and Value={1}".format(len(lstSHADOW_LOG_TABLE[index_shadow_log][1]), lstSHADOW_LOG_TABLE[index_shadow_log][1]))
for l_inner_element in (lstSHADOW_LOG_TABLE[index_shadow_log:][1]):
if(lstSHADOW_LOG_TABLE[index_shadow_log][1] == lstCAN_LOG_TABLE[index_can_log][1]):
#Some Calculation
else:
break
OUTPUT:
Length=3 and Value=340
Traceback (most recent call last):
for l_inner_element in (lstSHADOW_LOG_TABLE[index_shadow_log:][1]):
IndexError: list index out of range
EDITED FROM HERE (CODE MODIFIED TO INCORPORATE SUGGESTION):
The List "lstSHADOW_LOG_TABLE" is a List of Lists. Now let us say I want the comparison to start fresh from index "index_shadow_log" (SubList "index_shadow_log" onwards)
for l_inner_element in (lstSHADOW_LOG_TABLE[index_shadow_log:]):
Thanks for your answers, I now understood that the meaning of this for loop would be start iteration for List "lstSHADOW_LOG_TABLE" starting from index "index_shadow_log:"
This is my extracted code:
for index in range(len(lstCAN_LOG_TABLE)):
for l_index in range(len(lstSHADOW_LOG_TABLE)):
#print(lstSHADOW_LOG_TABLE[l_index][0])
#print(lstSHADOW_LOG_TABLE[l_index][1])
if(lstSHADOW_LOG_TABLE[l_index][1] == lstCAN_LOG_TABLE[index][1]): #Consider for comparison only CAN IDs
print("matching")
#print(lstCAN_LOG_TABLE[index][0])
#print(lstSHADOW_LOG_TABLE[l_index][0])
index_can_log = index #Position where CAN Log is to be compared
index_shadow_log = l_index #Position from where CAN Shadow Log is to be considered
print("Length={0} and Value={1}".format(len(lstSHADOW_LOG_TABLE[index_shadow_log][1]), lstSHADOW_LOG_TABLE[index_shadow_log][1]))
bMatchFound = 1
for l_inner_element in (lstSHADOW_LOG_TABLE[index_shadow_log:]): #Start comparison
if(lstSHADOW_LOG_TABLE[index_shadow_log][1] == lstCAN_LOG_TABLE[index_can_log][1]): #Compare individual element
dump_file.write("\n")
dump_file.write("SHADOW: " + str(lstSHADOW_LOG_TABLE[index_shadow_log])) #Dump if equal
writer_two.writerow(lstSHADOW_LOG_TABLE[index_shadow_log][0]) #Update CSV File
dump_file.write("\n")
dump_file.write("CAN: " + str(lstCAN_LOG_TABLE[index_can_log])) #Dump if equal
writer_one.writerow(lstCAN_LOG_TABLE[index_can_log][0]) #Update CSV File
if(index_can_log < (input_file_one_row_count - 1)): #Update CAN LOG Index
index_can_log = index_can_log + 1
if(index_can_log >= (input_file_one_row_count - 1)):
break
else:
bMatchFound = 0
break
if(bMatchFound == 0):
break
dump_file.close()
I need to get rid of parenthesis (Sorry coming from C/C++ background we love braces and parenthesis :-P) and make the code a lot cleaner. Thanks all for your suggestions

Compare:
lstSHADOW_LOG_TABLE[index_shadow_log][1]
with
lstSHADOW_LOG_TABLE[index_shadow_log:][1]
The first indexes lstSHADOW_LOG_TABLE, then indexes whatever that returned. The second slices lstSHADOW_LOG_TABLE; this returns a new list. You then indexed that sliced list. If that sliced list has only 1 element, then indexing the second is going to fail.
You really need to cut back on the parentheses here, and simplify the code somewhat. Use a temporary variable to store the indexed element:
value = lstSHADOW_LOG_TABLE[index_shadow_log][1]
if value:
print("Length={0} and Value={1}".format(len(value), value))
for l_inner_element in value:
if value == lstCAN_LOG_TABLE[index_can_log][1]:
#Some Calculation
else:
break

Related

Always have this error 'IndexError: string index out of range', when i have taken into consideration of index range

Need to write a program that prints the longest substring of variable, in which the letters occur in alphabetical order.
eg. s = 'onsjdfjqiwkvftwfbx', it should returns 'dfjq'.
as a beginner, code written as below:
y=()
z=()
for i in range(len(s)-1):
letter=s[i]
while s[i]<=s[i+1]:
letter+=s[i+1]
i+=1
y=y+(letter,)
z=z+(len(letter),)
print(y[z.index(max(z))])
However, above code will always return
IndexError: string index out of range.
It will produce the desired result until I change it to range(len(s)-3).
Would like to seek advice on:
Why range(len(s)-1) will lead to such error message? In order to take care of index up to i+1, I have already reduce the range value by 1.
my rationale is, if the length of variable s is 14, it has index from 0-13, range(14) produce value 0-13. However as my code involves i+1 index, range is reduced by 1 to take care of this part.
How to amend above code to produce correct result.
if s = 'abcdefghijklmnopqrstuvwxyz', above code with range(len(s)-3) returns IndexError: string index out of range again. Why? what's wrong with this code?
Any help is appreciated~
Te reason for the out of range index is that in your internal while loop, you are advancing i without checking for its range. Your code is also very inefficient, as you have nested loops, and you are doing a lot of relatively expensive string concatenation. A linear time algorithm without concatenations would look something like this:
s = 'onsjdfjqiwkvftwfbcdefgxa'
# Start by assuming the longest substring is the first letter
longest_end = 0
longest_length = 1
length = 1
for i in range(1, len(s)):
if s[i] > s[i - 1]:
# If current character higher in order than previous increment current length
length += 1
if length > longest_length:
# If current length, longer than previous maximum, remember position
longest_end = i + 1
longest_length = length
else:
# If not increasing order, reset current length
length = 1
print(s[longest_end - longest_length:longest_end])
Regarding "1":
Actually, using range(len(s)-2) should also work.
The reason range(len(s)-1) breaks:
For 'onsjdfjqiwkvftwfbx', the len() will be equal to 18. Still, the max index you can refer is 17 (since indexing starts at 0).
Thus, when you loop through "i"'s, at some point, i will increase to 17 (which corresponds to len(s)-1) and then try access s[i+1] in your while comparison (which is impossible).
Regarding "2":
The following should work:
current_output = ''
biggest_output = ''
for letter in s:
if current_output == '':
current_output += letter
else:
if current_output[-1]<=letter:
current_output += letter
else:
if len(current_output) > len(biggest_output):
biggest_output = current_output
current_output = letter
if len(current_output) > len(biggest_output):
biggest_output = current_output
print(biggest_output)

Python3: Change the items on a list with function and while loop. Why is my code not running properly?

While doing the following task I found my code not running on Jupiter notebooks properly (have restarted the Kernel several times already):
Function Challenge: create replacement function
Create a function, str_replace, that takes 2 arguments: int_list and
index
int_list is a list of single digit integers
index is the index that will be checked - such as with int_list[index]
Function replicates purpose of task "replace items in a list" above
and replaces an integer with a string "small" or "large"
return int_list
Test the function!
My goal is to change all the elements of the list [0,1,2,3,4] to ["small","small", "small","small","small"] with the following code:
int_list=[0,1,2,3,4]
index=0
def str_replace(int_list,index):
if index <5:
int_list[index]="small"
return int_list
else:
int_list[index]="large"
return int_list
str_replace(int_list,index)
while index <=4:
index+=index
str_replace(int_list,index)
When I run it, it keeps running and not giving me back any output. However if I run everything but the last while loop I get: ["small",1,2,3,4]. Can anybody help me understanding why this happens?
You are in an infinite loop because index is always smaller than 4,
you do index += index but because index is 0 nothing adds up and you stay in the loop.
If you change it to index += 1instead - that should solve your problem.
Also to not get an out of range error change it to while index < 4: or alternatively put the index +=1 at the bottom of the loop.
You are in an infinite loop : index is always <= 4. See : index is initialised to 0 and the new assignment index+=index will never change the value of index to higher than 0. Did you mean index += 1 ?
i think the problem was with the return statement with every chamge
int_list=[0,1,2,3,4]
index=0
def str_replace(int_list,index):
if index <5:
int_list[index]="small"
else:
int_list[index]="large"
while index <=4:
str_replace(int_list,index)
index+=1
print(int_list)
An alternative is to use
[ 'small' if index < 5 else 'large' for index in int_list]
int_list=[0,1,2,3,6]
index=0
def str_replace(int_list,index):
if int_list[index] < 5:
int_list[index] = "small"
else:
int_list[index] = "large"
while index <=4:
str_replace(int_list,index)
index+=1
print(int_list)

How does this code not get an index error when the loop variable gets to the end of the range in a for loop?

This was a HW problem in edX that asked me to determine how many times the word "bob" occurred within some string. I got to a solution, but I'm confused as to why it works. For code(1):
CODE(1)
s = 'azcbobobegghakl'
count = 0
for i in range(len(s)):
if s[i:i+3] == "bob":
count += 1
print(count)
In the same HW, there was a problem that asked me to find the longest sub-string in alphabetical order within some string. In the beginning of finding the solution, I was faced with an index error because I was trying to refer to an index that was out of range; shown in this code:
CODE(2)
s = 'azcbobobegghakl'
temp = ''
longest = ''
for i in range(len(s)):
if s[i] <= s[i+1]:
temp += s[i+1]
if len(temp) > len(longest):
longest = temp
else:
temp = s[i+1]
print(longest)
ERROR(2)
Traceback (most recent call last):
File "C:/Users/vchi/PycharmProjects/edX/introduction.py", line 5, in <module>
if s[i] <= s[i+1]:
IndexError: string index out of range
Why is it that CODE(1) is not faced with the the same kind of error that CODE(2) received when i > len(s)-4 and s[i:i+3] tries to refer to things that are out of bounds? Thank you in advance!
Python slicing is weird in a lot of ways, and this is one that kind of proves this.
With strings in python if the slice goes out of range, it will just set the "end" of the slice as the last viable index so if we did something like:
a = 'boboabcdef'
and then did:
b = a[4:12]
we would just get b is equal to 'abcdef', as it would just disregard the rest of the string.
But when it comes to indexes for lists, python has a much stricter interpretation, as it would be incredibly difficult to debug a program where a list could go out of index with no errors or warnings.

Code to check all list elements are same returns IndexError?

I know the index goes over the index of the last member of the group doing it like this but how do I make the function work properly?
Anyway, the function is meant to check if all the members of a list are the same. I have the same problem with another function which is meant to check if the list is in order. It works with everything else but when it's all same numbers it doesn't.
i = 0
while i < len(list1):
if list1[i] == list1[i + 1]:
i += 1
else:
return False
return True
Error message is: "IndexError: list index out of range"
When i reaches the maximum index within list1, obviously list1[i+1] will be out of bounds. The immediate fix is to start at 1 (and then of course compare downwards) or stop at len(list1)-1.
But you can simplify by comparing all indices to the zeroth.
all([list1[0] == x for x in list1[1:]])
or as a longhand loop
for elem in list1[1:]:
if elem != list1[0]:
return False
return True
The error itself is coming from the line
if list1[i] == list1[i+1]
The portion of the line above is going out of range. An easy fix is to change the while statement to this:
while i < (len(list1)-1):
I believe that should still have the same result as you desire.
Be careful about accessing future items in a list with a while loop.

iterating over a changeable iterator in every iteration

I am trying to implement the code below, and I'm getting an error of
"index is out of range". I think I am getting the error because the for loop saved the value of the length of the array, while I changed it inside the loop itself.
I can't figure out how to solve it using a for loop.
I did solve it using a recursive way, but it was computationally expensive and I am dealing with billions of words. BTW, the Comp function only returns a pool if the 2 words having the same sentence, so I believe it doesn't effect.
I am using Python-3, pycharm.
def reg(array,n):
f=open(r"C:\Users\Ali\Desktop\love.txt","w")
length= len(array)
if length==1:
return array
k=0
for item in range (length-1):
k+=1
for j in range(k,length):
if Comp(array[item][0],array[j][0])>=n:
f.write(str("\n"))
f.write(str(array[item][1]))
f.write(str("\n"))
f.write(str(array[j+k ][1]))
array[k+j]=array.pop()
length-=1
break
f.close()
pass
Instead of modifying the array, just keep track of your effective last index and break out when you hit it. Something like (untested)
k = 0
last_index = len(array) - 1
for item in range(length - 1):
if item > last_index:
break
k += 1
# ....
array[k+j] = array[last_index]
last_index -= 1
break

Categories