Search code examples
pythonloopsfor-loopgenerator

Continue the loop once the item meets a condition using a python generator


I have a list of random numbers. I want to refine the list so that there is no pair of numbers that has a product of 0.5. I am trying to use the next method for python generator so that I can continue the loop as soon as the condition is met. Another reason is that I want to avoid a nested for-loop, so that the code can continue the main loop when the condition is met.

It's worth noting that in my real case the computational cost to check the condition is very expensive, and this is why I want to use a generator, so that I can continue the loop as soon as the condition is met, instead of checking the condition with all current existing numbers in refined_list. Here I just use a simple condition i * j == 0.5 as an example.

Below is my code

import random

rands = [random.uniform(0,1) for _ in range(100)]
refined_list = []
for i in rands:
    if refined_list: # Make sure the refined list is not empty
        if next(j for j in refined_list if i * j == 0.5):
            continue
    refined_list.append(i)

print(refined_list)

However, I get the StopIteration error once the condition is met.

So how should I continue the loop using a generator? Or is there a better way to do this?


Solution

  • The problem is in next it self, either your condition is true, either is raises the exception


    You may use any

    for i in rands:
        if refined_list:  # Make sure the refined list is not empty
            if any(j for j in refined_list if i * j == 0.5):
                continue
        refined_list.append(i)
    

    You could refactor the condition to group the condition, and get

    for i in rands:
        if not (refined_list and any(j for j in refined_list if i * j == 0.5)):
            refined_list.append(i)