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