I'm trying to build a function to return an Iterator with no duplicated float values, its working, but there is a better way of handling this duplicated values?

from collections import deque
from collections.abc import Iterator
from locale import atof

def get_non_repeated_numbers(n: int) -> Iterator[float]:
    Yields n float values to return Iterator
    :param n: int
    :return: Iterator[float]
    numbers = deque()
    for i in range(n):
        while True:
                number = atof(
                    input(f'Enter the {i + 1}º number:\n-> ')
                if number not in numbers:
                    yield number
                    raise ValueError
            except ValueError:
                print('Invalid number! Try again...\n')
  • 1
    \$\begingroup\$ So the user has to enter n distinct numbers? I wonder what the purpose of that iterator is. \$\endgroup\$
    – Martin R
    Sep 12 at 14:57
  • \$\begingroup\$ What is your locale? \$\endgroup\$
    – Reinderien
    Sep 12 at 18:45
  • \$\begingroup\$ Probably pt-BR \$\endgroup\$
    – Reinderien
    Sep 12 at 18:47
  • 1
    \$\begingroup\$ It is pt-BR, im setting 'pt_BR.UTF-8' \$\endgroup\$
    – eddyxide
    Sep 13 at 1:19

1 Answer 1


Overall pretty reasonable.

Use a set() instead of a deque() so that you have O(1) amortised time complexity for insertion and membership checks.

Since you have to build up a set anyway: if it's unimportant to process the numbers as they come in (which it probably isn't, but you haven't shown us) and the order of the numbers doesn't matter, just drop the iterator and return the set.

If the order is important, you could build up and then return the keyset of an OrderedDict (or a regular dict that guarantees insertion order preservation for sufficiently modern Python).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.