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