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