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