Level 5 : Filtering numbers in an iterator.


class FilterIterator:
    def __init__(self, data, condition):
        self.data = data
        self.condition = condition
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        while self.index < len(self.data):
            value = self.data[self.index]
            self.index += 1
            if self.condition(value):
                return value
        raise StopIteration

it = iter(FilterIterator([1, 2, 3, 4, 5, 6], lambda x: x % 2 == 0))
print(list(it))

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