0

I wrote this code which is a generator function that loops over the input iterable sequence, yielding one element at a time, but skipping duplicates. It then prints them.

seen = set()
    for n in iterable:
        if n not in seen:
            seen.add(n)
            yield n
numbers = [4, 5, 2, 6, 2, 3, 5, 8]
nums = unique(numbers)
print(next(nums))
print(next(nums))
print(next(nums))
print(next(nums))
print(next(nums))
print(next(nums))
print(next(nums))

things = unique(['dog', 'cat', 'bird', 'cat', 'fish'])
print(next(things))
print(next(things))
print(next(things))
print(next(things))

Right after the print(next(nums)), there is a stopiteration which I am ok with and is expected. My question is how to get past this to move on to the animals list.

My second question is whether there is any way to write this code without creating a list and returning the values.

user10019227
  • 117
  • 1
  • 2
  • 7

1 Answers1

0

You can pass None as the second argument to next so that instead of raising StopIteration, next will return None as the default value, so you can write your iteration as a loop, and have it break the loop when the iterator is exhausted.

while True:
    num = next(nums, None)
    if num is None:
        break
    print(num)

Alternatively, you can catch the exception in a try block:

while True:
    try:
        print(next(nums))
    except StopIteration:
        break
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Where would I put this block. I put it right before I defined numbers and I got a ValueError: generator already executing – user10019227 Jul 16 '18 at 02:06
  • @user10019227 The core idea of the challenge is to use `next(nums, None)` so it won't throw an error, then you handle it yourself. And you have to handle it yourself. – user202729 Jul 16 '18 at 02:14
  • @user10019227 What I wrote is meant to replace all your `print(next(nums))` statements. Putting it before numbers are defined simply wouldn't make sense, since it's based on those numbers. – blhsing Jul 16 '18 at 02:14