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