Home > OS >  How to iterate and loop through every array value in python
How to iterate and loop through every array value in python

Time:06-29

    while True:
        for i in range(len(listing_ids)):
            response = requests.get(f'apiurl/{listing_ids[i]}/pr', cookies=cookies, headers=headers) 
            response = response.json()
            print(response['jsonValue'])
            break

I have an array currently as listing_ids and within this array has an undetermined count of values that I want to use within a request URL then price the response then loop back through until the the last value within the array was used. How can I format this? Currently it just infinitely loops with the 1st value ONLY

CodePudding user response:

From what you're describing, just edit your code to look like this:

for i in range(len(listing_ids)):
    response = requests.get(f'apiurl/{listing_ids[i]}/pr', cookies=cookies, headers=headers) 
    response = response.json()
    print(response['jsonValue'])

This will go through every value in your array, and print out response['jsonValue'].

In your original code, the break will make the loop stop after 1 iteration - hence why it loops the first value only. And the while loop will make this occur infinitely.

CodePudding user response:

The break statement in your code breaks the for loop after it's first iteration, then because the while loop is still running the for loop starts all over again. Step-by-step what's happening is:

  1. The while loop starts its first iteration
  2. The for loop starts its first iteration
  3. First request is made for the first id
  4. First JSON value is printed
  5. break is executed - start from step 2 again

If I understood your intent correctly you can just remove the while loop and the break statement. Your code will then iterate over the list and make a request for each id.

  • Related