do variables need to be instantiated before loop python?

You want to just add one list to another list, but you’re doing it wrong. One way to do that is:

the_next_hundred_records = subreddit_data.json()['data']['children']
subreddit_content.extend(the_next_hundred_records)

compare append and extend at https://docs.python.org/3/tutorial/datastructures.html

What you did with append was add the full list of the next 100 as a single sub-list at position 101. Then, because list.append returns None, you set subreddit_content = None

Let’s try some smaller numbers so you can see what’s going on in the debugger. Here is your code, super simplified, except instead of doing requests to get a list from subreddit, I just made a small list. Same thing, really. And I used multiples of ten instead of 100.

def do_query(start):
    return list(range(start, start+10))

# content is initialized to a list by the first query
content = do_query(0)
while len(content) < 50:
    next_number = len(content)
    # there are a few valid ways to add to a list. Here's one.
    content.extend(do_query(next_number))
    
for x in content:
    print(x)

It would be better to use a generator, but maybe that’s a later topic. Also, you might have problems if the subreddit actually has less than 500 records.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top