Reputation: 735
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
Upvotes: 0
Views: 403
Reputation: 1535
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
Upvotes: 0
Reputation: 563
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
Upvotes: 0
Reputation: 1876
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])
Upvotes: 1