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