List Index Error in Python - python

In this program, I want to search for a Number from a list. When I search a number that is in the list, it works correctly.
But if I search a number that it is not in list, it gives me this Error:
Traceback (most recent call last):
File "fourth.py", line 12, in <module>
if(AranaElemean==liste[i]):
IndexError: list index out of range
liste=[12,23,3489,15,345,23,9,234,84];
Number=11;
i=0;
Index=0;
isWhileActive=0;
while (i<len(liste) and Number!=liste[i]):
i=i+1;
if(Number==liste[i]):
Index=i;
isWhileActive=1;
else:
Index=0;
if(isWhileActive==0 and i!=0):
print("Please Enter Valid Number.");
else:
print("Index:",Index);

That's because i goes from 0 to len(liste) and inside the while loop you are increasing the i by one. So when it doesn't find the desired number and i gets the value i = len(liste), you increae it by 1 in the loop so you get the error because it exceeds the range of the list.
you can use the following
while (i<len(liste)):
if(Number==liste[i]):
Index=i;
isWhileActive=1;
break
else:
Index=0;
i += 1

Your condition should be:
while (i<len(liste)-1 and Number!=liste[i])
This is because Python list indexing begins at 0.
Therefore, for a list of length n you need to index from 0 to n-1.

Related

What is the error in this programme of finding the number of times we get consecutive equal values

def get_count(num_list):
count=0
for i in num_list:
if (i==num_list[i+1]):
count=count+1
else:
pass
return count
list=[1,1,5,100,-20,-20,6,0,0]
getCount=get_count(list)
print(getCount)
Traceback (most recent call last):
File "C:/Users/SHIVAM TYAGI/PycharmProjects/infiTQ/Day3Excercise17.py", line 12, in <module>
getCount=get_count(list)
File "C:/Users/SHIVAM TYAGI/PycharmProjects/infiTQ/Day3Excercise17.py", line 5, in get_count
if (i==num_list[i+1]):
IndexError: list index out of range
In your code, you are iterating over the elements of num_list, and trying to compare it with an element of num_list the index of which does not exist. Hence the error.
You need to iterate over the indices, till last but one element.
def get_count(num_list):
count=0
for i in range(len(num_list)-1): # Looping from index 0 to length-1
if (num_list[i]==num_list[i+1]):
count=count+1
return count
list=[1,1,5,100,-20,-20,6,0,0]
getCount=get_count(list)
print(getCount)

lndexError: list index out of range

I need to generate a string from random letters given in list take_from. The first time the function was executed it generated a phrase but all my following tries prompted an error "list index out of range". I can`t understand this error in my case and I tried while loop instead of for loop but it did not work either.
from random import randint
def make_a_phrase():
random_string = ''
take_from = ['a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','v','u','w','x',
'y','z',' ']
for i in range(28):
random_string = random_string + take_from[randint
(0,len(take_from))]
return random_string
From the docs
random.randint(a, b)
Return a random integer N such that a <= N <= b.
Alias for randrange(a, b+1).
Therefore you can get values from 0 to len(take_from) - inclusive the endpoints - which in case of the upper bound would be out of list's index range as it is zero based and as such only has len(take_from) - 1 elements
In Python, lists are indexed with integers ranging from 0 to 1 less than the length of the list. E.g., a list with 10 items in it would have indexes from 0 to 9.
Your call to randint() attempts to get indexes from zero to the full length of the list, which will cause this exception. Change it to:
for i in range(28):
random_string = random_string + take_from[randint
(0,len(take_from)-1)]
The reason this happens, is because the len returns the length, but the last index is always the length - 1 (since indices start from 0).
So eventually, the random integer that comes up is the length, and of course, there is no element at that number.
Here is a simple example:
>>> i = [1,2,3]
>>> len(i)
3
>>> i[len(i)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
However, if you -1 from the length you will get the last item:
>>> i[len(i)-1]
3
You should change your loop to say:
for i in range(0, len(take_from)):
You are currently experiencing an off-by-one error because you only have 27 elements in your list, not 28.
You could try something like this instead
from string import ascii_lowercase
import random
def make_a_phrase():
return ''.join(random.choice(ascii_lowercase + ' ') for i in range(28))

Indexing error scanning list

I apologize ahead of time for the basic nature of this question but I could really use a different set of eyes to see why I'm still getting an IndexError: list index out of range.
Here is my code:
def longestRun(L):
counter=1
ii=0
counts=[1]
while ii<=max(range((len(L)))):
if L[ii] <= L[(ii+1)]:
counter+=1
ii+=1
else:
ii+=1
counts.append(counter)
counter=1
continue
counts.sort()
return counts[-1]
It is supposed to count the longest streak of consecutive increases for a list of integers. I got it working by subtracting 1 from the while statement but then it will not always show the right answer because it won't go through the whole list.
Here is my specific error message:
IndexError
Traceback (most recent call last)
<ipython-input-76-1b4664f2fb31> in <module>()
----> 1 longestRun(L)
C:\Users\james_000\Desktop\longestRun.py in longestRun(L)
4 counts=[1]
5 while ii<=max(range((len(L)))):
----> 6 if L[ii] <= L[(ii+1)]:
7 counter+=1
8 ii+=1
Your while loop is while ii<=max(range((len(L)))): and then your if statement's condition accesses L[ii+1] which runs off the end of the array.
It's simple math. Let's say L is of length 10. That makes the last index 9. ii can eventually be 9, thus ii+1 is going to be out of range.

Nested list sorting in Python

This is a question of nested loop where I have to find the names of students in alphabetical order with 2nd lowest marks.
I am getting following error:
Traceback (most recent call last):
File "solution.py", line 12, in <module>
if (l[i][0]==l[0][0]):
IndexError: list index out of range
Following is my complete code.
l=list()
p=list()
q=list()
for i in range (int(raw_input())):
p=[raw_input(),int(raw_input())]
p.reverse()
l.append(p)
l.sort()
print len(l)
for i in range(0,len(l)):
print "i= ",i
if (l[i][0]==l[0][0]):
l.remove(l[i])
print l
for i in range(0,len(l)):
if (l[i][0]==l[0][0]):
q.append(l[i][1])
q.sort()
for i in range(0,len(q)):
print q[i]
I have even printed the index which shows the values are in range. Please run the function to find the following output:
4
i= 0
i= 1
i= 2
i= 3
I will happy if I get any better method from my the community ,But my main concern is the error I am getting "Index Out of Range" .It doesn't seem right here
The problem is that you are removing items from a loop. The thumb rule is that you shall never remove items from a list while iterating over it.
I don't really understand your code right now, but you can just change the way you are doing the first loop and apply the same logic for the next ones, at least you will have what you want.
The idea here is that with the while statement, after each iteration, you will have another verification of the size of the list. Meanwhile with the for loop, only at the first time, since range will return a list and the for loop will just iterate over the list which was already created.
l=list()
p=list()
q=list()
for i in range (int(raw_input())):
p=[raw_input(),int(raw_input())]
p.reverse()
l.append(p)
l.sort()
print len(l)
i = 0
while i < len(l):
print "i= ",i
if (l[i][0]==l[0][0]):
l.remove(l[i])
i += 1
print l
You are using remove, because of that l, in some moment, have less elements than you expect.

List Index Out Of Range : 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

Categories