Level 3 : Fibonacci sequence iterator.


class FibonacciIterator:
    def __init__(self, n):
        self.a, self.b = 0, 1
        self.n = n
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.count >= self.n:
            raise StopIteration
        self.count += 1
        self.a, self.b = self.b, self.a + self.b
        return self.a

it = iter(FibonacciIterator(5))
print(list(it))

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