This loop is indeed not exceeding the range of the list:
for i in range(len(my_list)):
Within that loop, you can access list elements using i
as the index safely. But that’s not what you’re doing, you’re using hard-coded index values:
motMake = motordata.get('displayAttributes')[0]['value'] or None
motModel = motordata.get('displayAttributes')[1]['value'] or None
motYear = motordata.get('displayAttributes')[2]['value'] or None
motMilage = motordata.get('displayAttributes')[3]['value'] or None
motFuel = motordata.get('displayAttributes')[4]['value'] or None
So “for each item in the list” you’re telling the code to “give me the first 5 items”. You’re explicitly telling the code to access the second item in a list that you know has only one item. So, you get an exception.
It looks like you don’t want a loop at all, since you’re never actually using i
and always over-writing the same variables in the loop. Instead, check the length of the list before accessing each of the 5 hard-coded index values. Something like this:
my_list = motordata['displayAttributes']
length = len(my_list)
if length > 0:
motMake = motordata.get('displayAttributes')[0]['value']
if length > 1:
motModel = motordata.get('displayAttributes')[1]['value']
if length > 2:
motYear = motordata.get('displayAttributes')[2]['value']
if length > 3:
motMilage = motordata.get('displayAttributes')[3]['value']
if length > 4:
motFuel = motordata.get('displayAttributes')[4]['value']
0
solved Why am I getting IndexError: list index out of range? [closed]