Python list index error in an if statement - python

I am not sure why I am getting this list index out of bounds error
Basically what is supposed to happen is I am sending my def a list of twitter userIds and then breaking them into chunks of 100 looking them up in twitter, then adding them to a dictionary using the userIds as the key. So lets say 00001 is johnny we look up 00001 get johnny and then make a dictionary with 00001, johnny. However the if statements don't seem to trigger.
Here is the code:
def getUserName(lookupIds):
l = len(lookupIds) # length of list to process
i = 0 #setting up increment for while loop
screenNames = {}#output dictionary
count = 0 #count of total numbers processed
print lookupIds
while i < l:
toGet = []
if l - count > 100:#blocks off in chunks of 100
for m in range (0,100):
toGet[m] = lookupIds[count]
count = count + 1
print toGet
else:#handles the remainder
r = l - count
print screenNames
for k in range (0,r):#takes the remainder of the numbers
toGet[k] = lookupIds[count]
count = count + 1
i = l # kills loop
screenNames.update(zip(toGet, api.lookup_users(user_ids=toGet)))
#creates a dictionary screenNames{user_Ids, screen_Names}
#This logic structure breaks up the list of numbers in chunks of 100 or their
#Remainder and addes them into a dictionary with their userID number as the
#index value Count is for monitoring how far the loop has been progressing.
print len(screenNames) + 'screen names correlated'
return screenNames
The error is as follows:
Traceback (most recent call last):
File "twitterBot2.py", line 78, in <module>
toPrint = getUserName(followingids)#Testing Only
File "twitterBot2.py", line 42, in getUserName
toGet[k] = lookupIds[count]
IndexError: list assignment index out of range

toGet is initialized to the empty list, and you're attempting to assign [0] a value. This is illegal. Use append instead:
toGet.append(lookupIds[count])

This is likely because you're attempting to lookup index zero when it doesn't exist. Example:
>>> x=[]
>>> x[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

def getUserName(lookUpIds):
blockSize = 100
screenNames = {}
indexes = xrange(0, len(lookUpIds), blockSize)
blocks = [lookUpIds[i:(i + blockSize)] for i in indexes]
for block in blocks:
users = api.lookup_users(user_ids=block)
screenNames.update(zip(block, users))
return screenNames

Related

Python Index error using generator with yield

I'm running this code and I get the values I want from it, but there is also an IndexError: tuple index out of range for lines 12 and 18
import statistics as st
def squares(*args):
i = 0
val = []
fin = []
val = args
while True:
avg = (st.mean(val))
fin = (avg - val[i]) ** 2 # line 12
yield fin
i += 1
mylist = squares(3, 4, 5)
for x in mylist: # line 18
print(x)
result:
1
0
1
Traceback (most recent call last):
File line 18, in <module>
for x in mylist:
File line 12, in squares
fin = (avg - val[i]) ** 2
IndexError: tuple index out of range
Base on your code there are some variables & methods that you did that I think you can also change. Like example on this one. I commented out your old code so you can see the changes & difference.
import statistics as st
def squares(*args):
#i = 0
#val = []
fin = []
val = args
for n in val:
avg = (st.mean(val))
fin = (avg - n) ** 2 # line 12, #val[i]
#i += 1
yield fin
mylist = squares(3, 4, 5)
for x in mylist: # line 18
print(x)
I can see here that you are trying to access every value of val with fin = (avg - val[i]) ** But you can also use a for loop with it & don't need for a i variable as index. Also what #schwobaseggl is correct, you get the error IndexError: tuple index out of range because you kept incrementing or adding up your i to the point where you are trying to access a value from your val variable that is beyond its length.
You can simplify the generator function:
import statistics as st
def squares(*args):
avg = st.mean(args)
for arg in args:
yield (avg - arg) ** 2
Note that in your original, you have an infinite loop (while True) that you never break and that keeps incrementing index i while the i-accessed sequence val does not grow. That was always an IndexError waiting to happen.

IndexError: list assignment index out of range - problem with Python code

I have started to write code in python for several days. I have some problem, and I don't have idea what is wrong with my code. I guess that this is really basic problem. Here is my code:
import os
arrayData = []
wt = []
def getData(inputFile):
if os.path.isfile(inputFile):
print("file exist")
with open(inputFile) as data:
for line in data:
arrayData.append(line.strip())
else:
print("file",inputFile,"doesn't exist")
def fcfs():
counter=1
index=0
wt[0] = 0
while counter <= 10000:
for i in range(1,100):
print(index, counter)
wt[i+counter]=int(wt[i+index-1])+int(arrayData[i+index-1])
index+=1
counter += 100
getData('input.txt')
fcfs()
and here is the error:
Traceback (most recent call last):
File "/root/studia/so_project/main.py", line 30, in <module>
fcfs()
File "/root/studia/so_project/main.py", line 20, in fcfs
wt[0] = 0
IndexError: list assignment index out of range
In the file which I'm using are some random numbers, and I want to sort it with some algorithms.
To add an item to a list, use append:
wt.append(0)
wt[0] = 0 works only if there is an item at position 0.

Python - Trying to transfer data between nested lists (IndexError: list assignment index out of range)

I am aware of what it means to be out of range when indexing, but I am struggling to see why my code is generating this error...
import random
howMany = random.randint(1,3)
oldList = [['a',1,2,3], ['b',1,2,3], ['c',1,2,3], ['d',1,2,3], ['e',1,2,3], ['f',1,2,3], ['g',1,2,3], ['h',1,2,3], ['i',1,2,3]]
newList = []
for i in range(0, howMany):
newList[i] = oldList[random.randint(0, len(oldList)-1)] # subtract one
You are getting the error because newList is empty (its length is 0). You are trying to access elements in it using an index, but there are no indices. Here's a simpler example of what's happening:
>>> newList = []
>>> i = 0
>>> newList[i] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
What you want to do is use append():
import random
howMany = random.randint(1,3)
oldList = [['a',1,2,3], ['b',1,2,3], ['c',1,2,3], ['d',1,2,3], ['e',1,2,3], ['f',1,2,3], ['g',1,2,3], ['h',1,2,3], ['i',1,2,3]]
newList = []
for i in range(0,howMany):
newList.append(oldList[random.randint(0, len(oldList)-1)]) # subtract one

Python Key Error can't parse fields

I'm writing a script and iterating over a list to turn it into a JSON. My code:
Mbody is the name of the list I'm pulling info from.
index = 38
payload = {}
i = 0
while i < Number_SKUs:
SKU_size = 2
size_index = 4
value_index = 1
time_index = 4
ms_index = 2
payload[i].sku = Mbody[index:(index + SKU_size*2)]
index = index + SKU_size*2
print(payload[i].sku)
i+=1
For some reason, this is resulting in
Traceback (most recent call last):
File "parser.py", line 101, in <module> payload[i].sku = Mbody[index:(index + SKU_size*2)]
KeyError: 0
I have searched on stack exchange and found several similar questions, but none of which answer mine. What's the best way to iterate over a list and parse the skus? This will become a JSON eventually, but I could work with it in an array for the time being and use a dict to put it into a JSON later.
In python you have to name the keys of a dictionary to interact with them.
p['a']['b']
# This is element b of p['a']
p['a'].b
# This is function b in object p['a']
Dotted notation is not available by default although some people have solutions to add that.
Ignoring those, we can make some changes to your code to start working with the usual notation.
index = 38
# This can just be a list, because i is continuous between 0 and Number_SKUs
payload = []
i = 0
while i < Number_SKUs:
SKU_size = 2
size_index = 4
value_index = 1
time_index = 4
ms_index = 2
# Each item is going to be a new dictionary, which we will
# eventually add the the list of payloads
new_payload = {}
# Now we can create a dict entry for key 'sku' in new_payload
new_payload['sku'] = Mbody[index:(index + SKU_size * 2)]
# We can't do this, because tag_size is undefined
#
# index = index + tag_size * 2
# We can't do this, because we have not yet added a 'tag' key
# to payload.
#
# print(payload[i]['tag'])
# Now append new_payload to payload
payload.append(new_payload)
i += 1

List assignment index out of range

My code is giving me the error of:
list_subs[n][4] = np.random.normal(list_subs[n][1], list_subs[n][2])
IndexError: list assignment index out of range.
I have searched for this error and i still can't find what is the problem.
Edit: Full Traceback
Traceback (most recent call last):
File "", line 420, in run_nodebug
File "C:\Documents and Settings\jhsilva\Desktop\Monte carlo\Teste.py", line 71, in
generateRandomNumbers(list_subs)
File "C:\Documents and Settings\jhsilva\Desktop\Monte carlo\Teste.py", line 41, in generateRandomNumbers
list_subs[n][4] = np.random.normal(list_subs[n][1], list_subs[n][2])
IndexError: list assignment index out of range
The Code
def generateRandomNumbers(list_subs):
for n in range(len(list_subs)):
string = list_subs[n][3]
string = string.lower()
if(string == "normal"):
list_subs[n][4] = np.random.normal(list_subs[n][1], list_subs[n][2])
print("Numero gerado:",list_subs[n][4])
variables = [v for v in variables if v not in special]
list_subs=[[0 for col in range(6)] for row in range(len(variables)-1)]
#This prints fine
print(len(list_subs))
#this prints fine too
print(list_subs[0][4])
for n in range(len(variables)):
if n>0:
(media,desviopadrao,distribuicao) = eval(input("For variable "+variables[n]+" input: median, std, distr \n"))
list_subs[n-1] = [variables[n], media, desviopadrao, distribuicao]
N = eval(input("Qual o numero de iteracoes que deseja:"))
Var = []
for n in range(N):
generateRandomNumbers(list_subs)
Var.append(calcEq(formula))
list_subs[n-1] = [variables[n], media, desviopadrao, distribuicao]
You are setting list_subs to be a list of lists of length 4. This means that the valid indeces are 0, 1, 2, 3. In generateRandomNumbers you access index 4, which is invalid.
Security note: Don't use eval(input(...)). If you want to parse numbers/tuples etc simply use ast.literal_eval, which is a safe alternative.

Categories