Home > Net >  Avoid dupplicates with the yield keword?
Avoid dupplicates with the yield keword?

Time:09-17

Hello is it possible to avoid duplicates in a yield generator? for example

def foo():
    for i in (1,1,1,2,3,4,5):
        #check if "i" have not been "yielded" yet?
        yield i 

gen = foo()
numbers = list(gen)
print(numbers)

>>>[1,2,3,4,5]

numbers = list(gen) is cheating, the goal is to do it within the function

CodePudding user response:

You can define foo as follows

def foo():
    seen = set()
    for i in (1, 1, 1, 2, 3, 4, 5):
        if i not in seen:
            seen.add(i)
            yield i

Keep in mind that sets are unordered. If order doesn't matter to you, then you can use:

def foo():
    for i in set([1, 1, 1, 2, 3, 4, 5]):
        yield i

But if you need the result to be in order, then you'll have to stick to the initial formulation.

  • Related