redwytnblakII
redwytnblakII

Reputation: 111

Index error when running a for loop based on len of a list

I'm working with a large json file with an object that has over 300 nodes. I'd like to compile these nodes in a list for later use.

I've written the below code to accomplish this but am having trouble with for loop at the end

import json

a = open('file.json')
data = a.read()
j = json.loads(data)
l = len(j['field']['items']) 

q = []
for i in range(l):
    m = j['field']['items'][i]['values'][0]['value']
    q.append(m)

From my understanding, i here represents the node number under the field object and it is pulling from the variable l (which is the number of nodes under the object).

I've tested by manually inputing numbers for i (0, 1, 2...358) and it works, but when I run the above loop, I get the following error:

IndexError: list index out of range

Am I missing something?

Upvotes: 1

Views: 528

Answers (1)

MattDMo
MattDMo

Reputation: 102862

You can iterate directly over the items in a collection instead of using an index. In your case,

import json

j = json.load("file.json")
items = j['field']['items'] 

q = []
for item in items:
    m = item['values'][0]['value']
    q.append(m)

This avoids list index out of range errors when trying to iterate using range(len(collection)).

Upvotes: 1

Related Questions