Skip to content
Advertisement

Python3 delete n amount of elements in list after every loop

I can request the stock of 250 products at once. There are around about 7500-8000 products, but the amount changes by the day. So I try to request 250 products, delete them and do this again until my list(all_sku) holds less than 250 items in it, so I know this is my last request.

Sounds pretty easy, but today e.g there are 7697 items, but I only get stock for 7250 items.

start_time = time.time()
for i in range(0, 40):
    all_values = []
    time_now = time.time()
    time.sleep(10)
    if time_now - start_time >= 480:
        stock_values = xxx.get_stockforitems(all_sku[:250], session_master)
        all_values.append(stock_values)
        print(len(all_sku), 'before deleting first 250 elements')
        del all_sku[:250]
        print(len(all_sku), 'after deleting first 250 elements')
    else:
        stock_values = xxx.get_stockforitems(all_sku[:250], session_master)
        all_values.append(stock_values)
        print(len(all_sku), 'before deleting first 250 elements')
        del all_sku[:250]
        print(len(all_sku), 'after deleting first 250 elements')
    if len(all_sku) <= 250:
        stock_values = xxx.get_stockforitems(all_sku[:len(all_sku)], session_master)
        all_values.append(stock_values)
        print(len(all_sku), 'values remaining')
        del all_sku[:len(all_sku)]
        print(len(all_sku), 'after deleting elements')
        break

console output:

1187 before deleting first 250 elements
937 after deleting first 250 elements
937 before deleting first 250 elements
687 after deleting first 250 elements
687 before deleting first 250 elements
437 after deleting first 250 elements
437 before deleting first 250 elements
187 after deleting first 250 elements
187 values remaining
0 after deleting elements

Probably the error is in the if < 250 condition

It’s my first time working with break statement, maybe there is my origin of all evil

Advertisement

Answer

It looks ok and the output seems to be as expected. My guess will be that perhaps you are not getting all the results from get_stockforitems. I would add printouts of how many items you get each time.

There are some issues with your code that does not affect correctness: the if and else branches seem identical. Why are they there? The range(0, 40) seems random – why not while len(all_sku) > 0:.

Also all this deleting business seems messy, why not

for i in range(0,len(all_sku),250): 
   batch = all_sku[i:i+250]
   get_stockforitems(batch...
Advertisement