Level 1 : Implementing an iterator that returns prime numbers.


class PrimeIterator:
    def __init__(self, n):
        self.n = n
        self.num = 1

    def __iter__(self):
        return self

    def __next__(self):
        self.num += 1
        while any(self.num % i == 0 for i in range(2, int(self.num ** 0.5) + 1)):
            self.num += 1
        if self.num > self.n:
            raise StopIteration
        return self.num

it = iter(PrimeIterator(10))
print(list(it))

Author: SandhyaR | Tags: iterator | 1859+ Python FAQs | Share
assignment-operator | loop | conditional-statement | raise | __all__-attribute | list-mutation | regular-expressions | data-structures | dictionary-comprehensions | python-django | slice | attribute | reading-and-writing-large-files-efficiently | recursion | sys | floats | precedence | oop | design-principle | regex | matrix | data-structure | sorted | odd-number | bitwise-operator | counter | pickling--unpickling | sum-function | immutable-data-type | string-iteration | round-function | list-comprehensions | heap-memory | class-and-instance-variable | objects | regular-expression | copy | memory-management | parsing-with-strptime | syntax | datatype | exception | identity-operator | set-operation | object-attribute | sets | encoding | string-formatting | string-manipulation | head-and-tail | higher-order-function | error | string-concatenation | syntax-error | list,-set,-and-dictionary-comprehensions | datetime | string | conversion | set | collections | split | data-types | data_structure | defining-functions | swapping | for | logical-operation | multiprocessing | postfix | exponentiation | dataframe-and-series-objects | async | sys-module | overriding-methods | formatting-with-strftime | exception-handling | boolean | lists | operations | multithreading | math | loops | basic | unit-testing | counter-function | implementation | gil | walking-through-directories-using-os.walk() | keyword | encapsulation | turtle | lambda | sorting-and-ranking | advanced-file-operations | staticmethod | why-use-multiprocessing-over-threading?-(gil) | numpy | oops | print-statement | reading-and-writing-files | type-conversion-and-casting | filter-function | syntaxerror | input-function | python-history | data-type | formal-and-actual-parameter | strings | assignment-operators | error-handling | numeric | mathematics | default-mutable-argument | working-with-binary-files-(rb,-wb) | parameter | control-flow | overflow | functional-programming | sorting | call | pep | python-module | thread | binary-operation | string-slicing | operand | array | tuple | quantifiers-(*,-+,-?,-{}) | decorator | operator-overloading | pass | built-in-function | version-check | reading:-read(),-readline(),-readlines() | compute | loop-control-statements | context-manager | goto-function | functional-programming | operators | typeerror | error-handling | import-method | aggregating-data-with-functools.reduce() | comprehension | matplotlib | name-mangling | recurssion | intering | loop-control | choice | dictionaries | data-structure | memory | logical-operators | arbitrary-arguments-(*args,-**kwargs) | slicing | dictionary | data-structures-in-python | namedtuple | anchors-(^,-$) | round | magic-method | enumerate() | working-with-file-paths | boolean-and-non-boolean | condition | format | function-and-scope | operator-and | difference-between-threads-and-processes | introduction-to-multiprocessing | string-method | sum() | logical-operator | threading | assert | default-arguments | method | debugging | int | python | literal-characters-and-special-characters | stack | file-handling | global-keyword | raise-statement | writing:-write(),-writelines() | multiple-inheritance | function | while-loop | mutable | append | classes | virtual-environment | built-in-function | python-syntax-and-structure | generators-in-python | lambda-function | feature | installation | static-method | iterable | mapping-function | list-method | creating-and-starting-threads | list-comprehension | input | precedence-and-associativity | python-operators | center | conditional-statements | operator | asyncio-module | floating-point-precision | decimal | python-repl | string-formatting | list-comprehension | access-modifier | statement | binary | opening-files-(open()) | polymorphism | random | match | shallow-copy | booleans | syntax-error | tuple-unpacking | iterators | file | asyncio | matrix-list-comprehension | filter | list | using-else-and-finally | method-overloading | lambdas | descriptors | string-methods | test-discovery | bitwise-operator | pseudocode | operator-or | boolean-masking | application | zip-function | software-design | complex-number | datetime.date,-datetime.time,-datetime.datetime | control-flow | arithmetic-expression | string-method | creating-custom-modules | comparison | exception-handling | type-conversion | dicts | else-statement | pandas | return-statement | rollback | nested-loop | benefit | map-function | join | print | def | python_version | built-in-modules | global-variable | collection | string-slicing | id-function | range | namespace | constructor | control-statement | indexing:-loc-vs-iloc | factorial-function | else | package-management | tuple-methods | indexing | comment | __init_subclass__ | frozenset | generator | methods | data-type-conversions | class-and-inheritance | with-statement | scientific-notation | global-variable | destructor | iterator | using-os-and-pathlib-modules | type-conversion | inherit | touples | using-yield-in-functions | update | random-function | conditional-statement | identifier | deep-copy | introduction-to-python | managing-directories-with-os-and-shutil | docstring | min-max-function | zip | function-argument | __future__ | identity-operators-(is,-is-not) | file-handling | dictionary-methods | input-function | math-copysign | filtering-and-indexing | list-slicing | tuples | global | mysql | complex | thread-synchronization | directory-operations | working-with-temporary-files-using-tempfile | thread-safe-data-structures-(queue.queue) | multiple-except-blocks | arithmetic-operation | version | expression | class-decorators | using-join()-and-is_alive()-methods | while-else-loop | class-and-object | generators | membership-operators-(in,-not-in) | class | command-line-parsing | integers | list-methods-and-slicing | bitwise | built-in | library | multiple-inheritance | key-value-pairs | escape-operator | while-loops | min-function | file_handling | variable | integer | module | lambda-functions | init | using-assertions-(assertequal,-assertraises) | fabs-function | list-indexing | indentation | list-vs-tuple | working-with-dates-and-times | inheritance | mathematical-function | introduction-to-threads | while-and-for-loop | virtual-environment | list-operation | expand-tab | list-join | using-map()-for-transformations | invalid-list | using-lists-as-stacks | immutability | time-series-with-pandas | type_conversion | using-the-threading-module | logical-operator | yield | interpreter | zfill-function | single-inheritance | identity-operator | joining-and-merging-dataframes | handling-missing-values-(fillna,-dropna) | functions | max-min | data-type ...