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