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