While-loop - IndexError: list assignment index out of range - python

I keep getting Index Errors when I try to use while loops in combination with lists.
I wrote the code some time ago, came back to it, but just couldn't wrap my head around it enough to find my mistake. Apparently, the error has something to do with my lists indexes being too small or too large.
indexes = []
#Or indexes[0], but this threw another error
indexes.append(decoded.find(special_string))
x=1
while indexes[x-1] > 0:
total = sum(indexes)
indexes[x] = decoded.find(special_string, total)
x+=1
print(indexes)
My goal is to find all substrings (special_string) in a string and get their indexes (please inform me if you know an easier way to do this). I want to write all indexes out into a list for further use.

I think the only change you need to make is from:
indexes[x] = decoded.find(special_string, total)
to:
indexes.append(decoded.find(special_string, total))
You can't assign indexes[x] since it doesn't exist.

Related

Basic Python - finding difference between elements in a list - IndexError

I'm trying to find the daily increase in a bank account for 5 days. I have a list created. I need to create a new list tracking those daily increases so that later on I can find an average increase, max increase, etc. The problem I'm having is I keep getting an Indexerror. Can anyone please help me? I'm getting very frustrated. I've done similar coding before (without determining difference between 2 elements) and I have no problem. The moment I add math to the module, it blows up.
Code is below (the reason I have all the print statements is a double-check to make sure the lists are correct):
acct_balance = [9852.24,9854.25,9954.24,9985.56,10056.98]
index = 0
total = 0
amt_increase = []
while index < len(acct_balance):
if index != 0:
change = acct_balance[index+1] - acct_balance[index]
amt_increase.append(change)
total = total + change
index = index + 1
print('Account balances: ',acct_balance)
print('Daily Increase: ',amt_increase)
print('Total Increases: ',total)
I then get the below error when I try to run it:
Traceback (most recent call last):
File "C:\Users\Rogue\Desktop\Rogue Help\HELP.py", line 9, in <module>
change = acct_balance[index+1] - acct_balance[index]
IndexError: list index out of range
This is for school, so I can't use coding I've never seen before, and therefore don't understand. Thank you!
Your loop is checking your list for an element that doesn't exist.
The length of your loop is five. So if you increment your index by one every iteration of the loop, you will eventually end up referencing an element [element 6] that doesn't exist in your list and python will throw an error saying "list index out of range"
If you see a "list index out of range" error again, I would check to make sure you didn't accidentally write your code to reference past the bounds of a list.
acct_balance = [9852.24,9854.25,9954.24,9985.56,10056.98]
acct_increase = []
for index, value in enumerate(acct_balance):
if index == 0:
continue
acct_increase.append(acct_balance[index] - acct_balance[index - 1])
They say there are two hard things in computer science: naming conventions, cache misses, and off-by-one errors.
Instead of looking forward in the array (which is causing you to look over the end), always look backwards after skipping the 0th element. Also dont use while loops for looping over arrays in python, always use for-each loops. Do I get your homework credit :)
You're making your loop too complicated, which makes it hard to think about how the indices work. Replacing it with a for loop should help clear up the logic:
amt_increase = []
for index in range(1, len(acct_balance)):
change = acct_balance[index] - acct_balance[index - 1]
amt_increase.append(change)
total += change
The problem in your original was that on the last step, you tried to access the next index, which doesn't exist. I've inverted that so that it checks the previous day instead, so that the limits of the range are easy to read.
If you want to go a step farther and feel comfortable with list comprehensions, you can turn the loop into a single expression (excepting calculating total, but you could do that later in a variety of ways):
amt_increase = [today - yesterday
for today, yesterday
in zip(acct_balance[1:], acct_balance[:-1])]
Zipping the sliced lists lets you line them up the right way.

Python 3 Error Missunderstanding (IndexError)

Here's my code
def abc(l,z):
L=[]
länge= len(L)
for x in range(0, länge+1):
L[x]+z
print(L)
abc(["1","2","3"],"-")
I want the program to output "1-2-3"
l in abc(l,z) should be a List out of Strings which combines "l" and "z" to a single String.
I'm getting an Index Error: list index out of range.
There are a couple of issues here.
First, range(0, länge+1) will stop at länge but your list only has indexes from 0 tolänge - 1, so that's one source for an IndexError.
Second, L[x]+z will give you another IndexError because L is empty but you try to access L[0] (and in the next iteration, where you don't get because of the error, L[1], L[2], and so on).
Third, even without an IndexError the statement L[x]+z will do nothing. You compute the value of L[x]+z but then you don't assign any variable to it, so it is immediately lost.
Fourth, in order to print your final result, put the call to print after the for loop, not inside. Consider using return instead of print if you actually want to do something with the result the function produces (make sure to educate yourself on the difference between print and return).
Fifth, you want to build a string, so the usage of the list L does not make much sense. Start with an empty string and add the current item from l and z to it in the loop body (coupled with a re-assignment in order to not lose the freshly computed value).
Lastly, there's no point in using range here. You can iterate over values in a list direclty by simply writing for x in l:.
That should give you enough to work with and fix your code for now.
(If you don't care why your function does not work and this is not an exercise, simply use str.join as suggested in the comments.)

moving multiple indexes using the pop function in python

How can I use the pop function in a loop to pop from a certain index to a certain index. I need to move the front end of a list to the end and then delete a specific index. Here is my code so far. The idea is to cycle through a list [1,2,3,4,5,6,7....] up until the inputted number. Then it is supposed to delete the inputted number that is the count. The issue arises when needing to move multiple items to the back of the list in the count using the pop function. This code runs for example using the input 7 as the list and 2 as the count,but not 7 as the list and 3 as the count because it can't move more than one index to the back of the list.
def counter(L,m)
for i in range(m):
if len(L) >= m:
del L[m-1]
L.append(L.pop(0))
print("removed this number")
return L
else:
if len(L) < m:
del L[m]
I'm confused. Your last line should cause an index error.
Are you trying to shorten a list to a specific index?
It sounds like you should use slices, though I don't understand exactly what you are trying to do.
truncated = L[m:]
L = L[:m]
for i in truncated:
print("removed this number") #probably want to use interpolation here as well
to move the front to the back use [::-1]

Index error: List index out of range happens at times

So, basically i want to know why this piece of code works at times... Sometimes it works just fine, and sometimes it brings that index error. I have a bidimensional list 4x100 with data. Im simply retrieving data from the third row to sum it all in 1 variable.
Here is the list:
a=4
lst = [[] for _ in xrange(a)]
wifi= Wireless('wlan0')
while i<100:
results = wifi.scan()
print cont
print "%-8.16s Scan completed :" % (wifi.ifname,)
for ap in results:
if ap.bssid==AP1:
lst[0].append(ap.quality.getSignallevel())
if ap.bssid==AP2:
lst[1].append(ap.quality.getSignallevel())
if ap.bssid==AP3:
lst[2].append(ap.quality.getSignallevel())
if ap.bssid==AP4:
lst[3].append(ap.quality.getSignallevel())
i=i+1
cont=cont+1
for j4 in range(0,100):
num7=num7+lst[3][j4]
As it has already been mentioned there is not enough information to tell you exactly why you have the index out of range error.
There are several possible reasons:
wifi.scan() does not return exactly 4 values in a list. This why the third list in lst is not of size 100. Just check the results list has exactly 4 values.
Not all if statements work due to some reason. You need to check the values of each ap item - just print them out and read through the values. The the constants AP1, AP2 etc - are they initialized properly?
Also I would use elif statements instead of just if. I think it will make the code more readable and nice.

IndexError on list.pop() in list comprehension

To learn python I am implementing Bulls and Cows. So I need to generate a 'random' number. I tried this:
possibilities = range(10)
number = "".join([str(possibilities.pop(random.choice(possibilities))) for i in range(4)])
Which I thought was a nice solution to the problem, but once in every couple of runs I get an IndexError on that line: IndexError: pop index out of range
So it looks like random.choice() gives me a non existent index. How come?
Or am I making a wrong assumption and is the problem something else entirely?
Come to think of it, I haven't got a clue how to debug a statement like this, any pointers on that?
Edit
My first solution was of the procedural kind:
for i in range(4):
idx = random.choice(possibilities)
number = number + str(possibilities[idx])
del possibilities[idx]
This code seems to do the exact same thing as the one-liner above, but has no problems whatsoever.
You aren't randomly choosing indices, you're choosing values from the list. What if you pick 9 after a lower number or two has been popped from the list?
Instead, use random.sample:
number = "".join(map(str, random.sample(range(10), 4)))

Categories