Level 5 : What happens when the following code is executed?


class CustomIterator:
    def __init__(self, values):
        self.values = values
        self.index = len(values)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index -= 1
        return self.values[self.index]

it = CustomIterator(["A", "B", "C"])
print(list(it))
print(list(it))

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